From bb6b2be7de280c3a9e37126259f1c68a0f2bf73e Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 23 Mar 2021 12:48:11 -0700 Subject: [PATCH 1/5] chore: reorder imports (#265) --- google/cloud/dialogflow_v2/__init__.py | 4 +- google/cloud/dialogflow_v2beta1/__init__.py | 4 +- synth.metadata | 427 +++++++++++++++++++- 3 files changed, 429 insertions(+), 6 deletions(-) diff --git a/google/cloud/dialogflow_v2/__init__.py b/google/cloud/dialogflow_v2/__init__.py index 758d431f3..574b1a369 100644 --- a/google/cloud/dialogflow_v2/__init__.py +++ b/google/cloud/dialogflow_v2/__init__.py @@ -228,7 +228,6 @@ "ConversationPhoneNumber", "ConversationProfile", "ConversationProfilesClient", - "ConversationsClient", "CreateCallMatcherRequest", "CreateContextRequest", "CreateConversationProfileRequest", @@ -285,6 +284,7 @@ "IntentView", "IntentsClient", "KnowledgeBase", + "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", @@ -371,5 +371,5 @@ "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "KnowledgeBasesClient", + "ConversationsClient", ) diff --git a/google/cloud/dialogflow_v2beta1/__init__.py b/google/cloud/dialogflow_v2beta1/__init__.py index 3c8f83e65..22d347629 100644 --- a/google/cloud/dialogflow_v2beta1/__init__.py +++ b/google/cloud/dialogflow_v2beta1/__init__.py @@ -318,9 +318,9 @@ "Intent", "IntentBatch", "IntentView", - "IntentsClient", "KnowledgeAnswers", "KnowledgeBase", + "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", @@ -415,5 +415,5 @@ "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "KnowledgeBasesClient", + "IntentsClient", ) diff --git a/synth.metadata b/synth.metadata index db81540e2..6a06ead8c 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,8 +3,8 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-dialogflow", - "sha": "85e86bb0b9c03497a52c08990a763d6a665f6c40" + "remote": "https://github.com/googleapis/python-dialogflow.git", + "sha": "4717cb2deeabf8a4226b27c9912cc809c5804936" } }, { @@ -49,5 +49,428 @@ "generator": "bazel" } } + ], + "generatedFiles": [ + ".coveragerc", + ".flake8", + ".github/CONTRIBUTING.md", + ".github/ISSUE_TEMPLATE/bug_report.md", + ".github/ISSUE_TEMPLATE/feature_request.md", + ".github/ISSUE_TEMPLATE/support_request.md", + ".github/PULL_REQUEST_TEMPLATE.md", + ".github/header-checker-lint.yml", + ".github/release-please.yml", + ".github/snippet-bot.yml", + ".gitignore", + ".kokoro/build.sh", + ".kokoro/continuous/common.cfg", + ".kokoro/continuous/continuous.cfg", + ".kokoro/docker/docs/Dockerfile", + ".kokoro/docker/docs/fetch_gpg_keys.sh", + ".kokoro/docs/common.cfg", + ".kokoro/docs/docs-presubmit.cfg", + ".kokoro/docs/docs.cfg", + ".kokoro/populate-secrets.sh", + ".kokoro/presubmit/common.cfg", + ".kokoro/presubmit/presubmit.cfg", + ".kokoro/publish-docs.sh", + ".kokoro/release.sh", + ".kokoro/release/common.cfg", + ".kokoro/release/release.cfg", + ".kokoro/samples/lint/common.cfg", + ".kokoro/samples/lint/continuous.cfg", + ".kokoro/samples/lint/periodic.cfg", + ".kokoro/samples/lint/presubmit.cfg", + ".kokoro/samples/python3.6/common.cfg", + ".kokoro/samples/python3.6/continuous.cfg", + ".kokoro/samples/python3.6/periodic.cfg", + ".kokoro/samples/python3.6/presubmit.cfg", + ".kokoro/samples/python3.7/common.cfg", + ".kokoro/samples/python3.7/continuous.cfg", + ".kokoro/samples/python3.7/periodic.cfg", + ".kokoro/samples/python3.7/presubmit.cfg", + ".kokoro/samples/python3.8/common.cfg", + ".kokoro/samples/python3.8/continuous.cfg", + ".kokoro/samples/python3.8/periodic.cfg", + ".kokoro/samples/python3.8/presubmit.cfg", + ".kokoro/test-samples.sh", + ".kokoro/trampoline.sh", + ".kokoro/trampoline_v2.sh", + ".pre-commit-config.yaml", + ".trampolinerc", + "CODE_OF_CONDUCT.md", + "CONTRIBUTING.rst", + "LICENSE", + "MANIFEST.in", + "docs/_static/custom.css", + "docs/_templates/layout.html", + "docs/conf.py", + "docs/dialogflow_v2/agents.rst", + "docs/dialogflow_v2/answer_records.rst", + "docs/dialogflow_v2/contexts.rst", + "docs/dialogflow_v2/conversation_profiles.rst", + "docs/dialogflow_v2/conversations.rst", + "docs/dialogflow_v2/documents.rst", + "docs/dialogflow_v2/entity_types.rst", + "docs/dialogflow_v2/environments.rst", + "docs/dialogflow_v2/intents.rst", + "docs/dialogflow_v2/knowledge_bases.rst", + "docs/dialogflow_v2/participants.rst", + "docs/dialogflow_v2/services.rst", + "docs/dialogflow_v2/session_entity_types.rst", + "docs/dialogflow_v2/sessions.rst", + "docs/dialogflow_v2/types.rst", + "docs/dialogflow_v2beta1/agents.rst", + "docs/dialogflow_v2beta1/answer_records.rst", + "docs/dialogflow_v2beta1/contexts.rst", + "docs/dialogflow_v2beta1/conversation_profiles.rst", + "docs/dialogflow_v2beta1/conversations.rst", + "docs/dialogflow_v2beta1/documents.rst", + "docs/dialogflow_v2beta1/entity_types.rst", + "docs/dialogflow_v2beta1/environments.rst", + "docs/dialogflow_v2beta1/intents.rst", + "docs/dialogflow_v2beta1/knowledge_bases.rst", + "docs/dialogflow_v2beta1/participants.rst", + "docs/dialogflow_v2beta1/services.rst", + "docs/dialogflow_v2beta1/session_entity_types.rst", + "docs/dialogflow_v2beta1/sessions.rst", + "docs/dialogflow_v2beta1/types.rst", + "docs/multiprocessing.rst", + "google/cloud/dialogflow/__init__.py", + "google/cloud/dialogflow/py.typed", + "google/cloud/dialogflow_v2/__init__.py", + "google/cloud/dialogflow_v2/proto/agent.proto", + "google/cloud/dialogflow_v2/proto/answer_record.proto", + "google/cloud/dialogflow_v2/proto/audio_config.proto", + "google/cloud/dialogflow_v2/proto/context.proto", + "google/cloud/dialogflow_v2/proto/conversation.proto", + "google/cloud/dialogflow_v2/proto/conversation_event.proto", + "google/cloud/dialogflow_v2/proto/conversation_profile.proto", + "google/cloud/dialogflow_v2/proto/document.proto", + "google/cloud/dialogflow_v2/proto/entity_type.proto", + "google/cloud/dialogflow_v2/proto/environment.proto", + "google/cloud/dialogflow_v2/proto/gcs.proto", + "google/cloud/dialogflow_v2/proto/human_agent_assistant_event.proto", + "google/cloud/dialogflow_v2/proto/intent.proto", + "google/cloud/dialogflow_v2/proto/knowledge_base.proto", + "google/cloud/dialogflow_v2/proto/participant.proto", + "google/cloud/dialogflow_v2/proto/session.proto", + "google/cloud/dialogflow_v2/proto/session_entity_type.proto", + "google/cloud/dialogflow_v2/proto/validation_result.proto", + "google/cloud/dialogflow_v2/proto/webhook.proto", + "google/cloud/dialogflow_v2/py.typed", + "google/cloud/dialogflow_v2/services/__init__.py", + "google/cloud/dialogflow_v2/services/agents/__init__.py", + "google/cloud/dialogflow_v2/services/agents/async_client.py", + "google/cloud/dialogflow_v2/services/agents/client.py", + "google/cloud/dialogflow_v2/services/agents/pagers.py", + "google/cloud/dialogflow_v2/services/agents/transports/__init__.py", + "google/cloud/dialogflow_v2/services/agents/transports/base.py", + "google/cloud/dialogflow_v2/services/agents/transports/grpc.py", + "google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/answer_records/__init__.py", + "google/cloud/dialogflow_v2/services/answer_records/async_client.py", + "google/cloud/dialogflow_v2/services/answer_records/client.py", + "google/cloud/dialogflow_v2/services/answer_records/pagers.py", + "google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py", + "google/cloud/dialogflow_v2/services/answer_records/transports/base.py", + "google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py", + "google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/contexts/__init__.py", + "google/cloud/dialogflow_v2/services/contexts/async_client.py", + "google/cloud/dialogflow_v2/services/contexts/client.py", + "google/cloud/dialogflow_v2/services/contexts/pagers.py", + "google/cloud/dialogflow_v2/services/contexts/transports/__init__.py", + "google/cloud/dialogflow_v2/services/contexts/transports/base.py", + "google/cloud/dialogflow_v2/services/contexts/transports/grpc.py", + "google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/client.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py", + "google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/conversations/__init__.py", + "google/cloud/dialogflow_v2/services/conversations/async_client.py", + "google/cloud/dialogflow_v2/services/conversations/client.py", + "google/cloud/dialogflow_v2/services/conversations/pagers.py", + "google/cloud/dialogflow_v2/services/conversations/transports/__init__.py", + "google/cloud/dialogflow_v2/services/conversations/transports/base.py", + "google/cloud/dialogflow_v2/services/conversations/transports/grpc.py", + "google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/documents/__init__.py", + "google/cloud/dialogflow_v2/services/documents/async_client.py", + "google/cloud/dialogflow_v2/services/documents/client.py", + "google/cloud/dialogflow_v2/services/documents/pagers.py", + "google/cloud/dialogflow_v2/services/documents/transports/__init__.py", + "google/cloud/dialogflow_v2/services/documents/transports/base.py", + "google/cloud/dialogflow_v2/services/documents/transports/grpc.py", + "google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/entity_types/__init__.py", + "google/cloud/dialogflow_v2/services/entity_types/async_client.py", + "google/cloud/dialogflow_v2/services/entity_types/client.py", + "google/cloud/dialogflow_v2/services/entity_types/pagers.py", + "google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py", + "google/cloud/dialogflow_v2/services/entity_types/transports/base.py", + "google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py", + "google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/environments/__init__.py", + "google/cloud/dialogflow_v2/services/environments/async_client.py", + "google/cloud/dialogflow_v2/services/environments/client.py", + "google/cloud/dialogflow_v2/services/environments/pagers.py", + "google/cloud/dialogflow_v2/services/environments/transports/__init__.py", + "google/cloud/dialogflow_v2/services/environments/transports/base.py", + "google/cloud/dialogflow_v2/services/environments/transports/grpc.py", + "google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/intents/__init__.py", + "google/cloud/dialogflow_v2/services/intents/async_client.py", + "google/cloud/dialogflow_v2/services/intents/client.py", + "google/cloud/dialogflow_v2/services/intents/pagers.py", + "google/cloud/dialogflow_v2/services/intents/transports/__init__.py", + "google/cloud/dialogflow_v2/services/intents/transports/base.py", + "google/cloud/dialogflow_v2/services/intents/transports/grpc.py", + "google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/client.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py", + "google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/participants/__init__.py", + "google/cloud/dialogflow_v2/services/participants/async_client.py", + "google/cloud/dialogflow_v2/services/participants/client.py", + "google/cloud/dialogflow_v2/services/participants/pagers.py", + "google/cloud/dialogflow_v2/services/participants/transports/__init__.py", + "google/cloud/dialogflow_v2/services/participants/transports/base.py", + "google/cloud/dialogflow_v2/services/participants/transports/grpc.py", + "google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/session_entity_types/__init__.py", + "google/cloud/dialogflow_v2/services/session_entity_types/async_client.py", + "google/cloud/dialogflow_v2/services/session_entity_types/client.py", + "google/cloud/dialogflow_v2/services/session_entity_types/pagers.py", + "google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py", + "google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py", + "google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py", + "google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/services/sessions/__init__.py", + "google/cloud/dialogflow_v2/services/sessions/async_client.py", + "google/cloud/dialogflow_v2/services/sessions/client.py", + "google/cloud/dialogflow_v2/services/sessions/transports/__init__.py", + "google/cloud/dialogflow_v2/services/sessions/transports/base.py", + "google/cloud/dialogflow_v2/services/sessions/transports/grpc.py", + "google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2/types/__init__.py", + "google/cloud/dialogflow_v2/types/agent.py", + "google/cloud/dialogflow_v2/types/answer_record.py", + "google/cloud/dialogflow_v2/types/audio_config.py", + "google/cloud/dialogflow_v2/types/context.py", + "google/cloud/dialogflow_v2/types/conversation.py", + "google/cloud/dialogflow_v2/types/conversation_event.py", + "google/cloud/dialogflow_v2/types/conversation_profile.py", + "google/cloud/dialogflow_v2/types/document.py", + "google/cloud/dialogflow_v2/types/entity_type.py", + "google/cloud/dialogflow_v2/types/environment.py", + "google/cloud/dialogflow_v2/types/gcs.py", + "google/cloud/dialogflow_v2/types/human_agent_assistant_event.py", + "google/cloud/dialogflow_v2/types/intent.py", + "google/cloud/dialogflow_v2/types/knowledge_base.py", + "google/cloud/dialogflow_v2/types/participant.py", + "google/cloud/dialogflow_v2/types/session.py", + "google/cloud/dialogflow_v2/types/session_entity_type.py", + "google/cloud/dialogflow_v2/types/validation_result.py", + "google/cloud/dialogflow_v2/types/webhook.py", + "google/cloud/dialogflow_v2beta1/__init__.py", + "google/cloud/dialogflow_v2beta1/proto/agent.proto", + "google/cloud/dialogflow_v2beta1/proto/answer_record.proto", + "google/cloud/dialogflow_v2beta1/proto/audio_config.proto", + "google/cloud/dialogflow_v2beta1/proto/context.proto", + "google/cloud/dialogflow_v2beta1/proto/conversation.proto", + "google/cloud/dialogflow_v2beta1/proto/conversation_event.proto", + "google/cloud/dialogflow_v2beta1/proto/conversation_profile.proto", + "google/cloud/dialogflow_v2beta1/proto/document.proto", + "google/cloud/dialogflow_v2beta1/proto/entity_type.proto", + "google/cloud/dialogflow_v2beta1/proto/environment.proto", + "google/cloud/dialogflow_v2beta1/proto/gcs.proto", + "google/cloud/dialogflow_v2beta1/proto/human_agent_assistant_event.proto", + "google/cloud/dialogflow_v2beta1/proto/intent.proto", + "google/cloud/dialogflow_v2beta1/proto/knowledge_base.proto", + "google/cloud/dialogflow_v2beta1/proto/participant.proto", + "google/cloud/dialogflow_v2beta1/proto/session.proto", + "google/cloud/dialogflow_v2beta1/proto/session_entity_type.proto", + "google/cloud/dialogflow_v2beta1/proto/validation_result.proto", + "google/cloud/dialogflow_v2beta1/proto/webhook.proto", + "google/cloud/dialogflow_v2beta1/py.typed", + "google/cloud/dialogflow_v2beta1/services/__init__.py", + "google/cloud/dialogflow_v2beta1/services/agents/__init__.py", + "google/cloud/dialogflow_v2beta1/services/agents/async_client.py", + "google/cloud/dialogflow_v2beta1/services/agents/client.py", + "google/cloud/dialogflow_v2beta1/services/agents/pagers.py", + "google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/agents/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/client.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/contexts/__init__.py", + "google/cloud/dialogflow_v2beta1/services/contexts/async_client.py", + "google/cloud/dialogflow_v2beta1/services/contexts/client.py", + "google/cloud/dialogflow_v2beta1/services/contexts/pagers.py", + "google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/conversations/__init__.py", + "google/cloud/dialogflow_v2beta1/services/conversations/async_client.py", + "google/cloud/dialogflow_v2beta1/services/conversations/client.py", + "google/cloud/dialogflow_v2beta1/services/conversations/pagers.py", + "google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/documents/__init__.py", + "google/cloud/dialogflow_v2beta1/services/documents/async_client.py", + "google/cloud/dialogflow_v2beta1/services/documents/client.py", + "google/cloud/dialogflow_v2beta1/services/documents/pagers.py", + "google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/documents/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/client.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/environments/__init__.py", + "google/cloud/dialogflow_v2beta1/services/environments/async_client.py", + "google/cloud/dialogflow_v2beta1/services/environments/client.py", + "google/cloud/dialogflow_v2beta1/services/environments/pagers.py", + "google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/environments/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/intents/__init__.py", + "google/cloud/dialogflow_v2beta1/services/intents/async_client.py", + "google/cloud/dialogflow_v2beta1/services/intents/client.py", + "google/cloud/dialogflow_v2beta1/services/intents/pagers.py", + "google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/intents/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/participants/__init__.py", + "google/cloud/dialogflow_v2beta1/services/participants/async_client.py", + "google/cloud/dialogflow_v2beta1/services/participants/client.py", + "google/cloud/dialogflow_v2beta1/services/participants/pagers.py", + "google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/participants/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/services/sessions/__init__.py", + "google/cloud/dialogflow_v2beta1/services/sessions/async_client.py", + "google/cloud/dialogflow_v2beta1/services/sessions/client.py", + "google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py", + "google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py", + "google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py", + "google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py", + "google/cloud/dialogflow_v2beta1/types/__init__.py", + "google/cloud/dialogflow_v2beta1/types/agent.py", + "google/cloud/dialogflow_v2beta1/types/answer_record.py", + "google/cloud/dialogflow_v2beta1/types/audio_config.py", + "google/cloud/dialogflow_v2beta1/types/context.py", + "google/cloud/dialogflow_v2beta1/types/conversation.py", + "google/cloud/dialogflow_v2beta1/types/conversation_event.py", + "google/cloud/dialogflow_v2beta1/types/conversation_profile.py", + "google/cloud/dialogflow_v2beta1/types/document.py", + "google/cloud/dialogflow_v2beta1/types/entity_type.py", + "google/cloud/dialogflow_v2beta1/types/environment.py", + "google/cloud/dialogflow_v2beta1/types/gcs.py", + "google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py", + "google/cloud/dialogflow_v2beta1/types/intent.py", + "google/cloud/dialogflow_v2beta1/types/knowledge_base.py", + "google/cloud/dialogflow_v2beta1/types/participant.py", + "google/cloud/dialogflow_v2beta1/types/session.py", + "google/cloud/dialogflow_v2beta1/types/session_entity_type.py", + "google/cloud/dialogflow_v2beta1/types/validation_result.py", + "google/cloud/dialogflow_v2beta1/types/webhook.py", + "mypy.ini", + "noxfile.py", + "renovate.json", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "scripts/decrypt-secrets.sh", + "scripts/fixup_dialogflow_v2_keywords.py", + "scripts/fixup_dialogflow_v2beta1_keywords.py", + "scripts/readme-gen/readme_gen.py", + "scripts/readme-gen/templates/README.tmpl.rst", + "scripts/readme-gen/templates/auth.tmpl.rst", + "scripts/readme-gen/templates/auth_api_key.tmpl.rst", + "scripts/readme-gen/templates/install_deps.tmpl.rst", + "scripts/readme-gen/templates/install_portaudio.tmpl.rst", + "setup.cfg", + "testing/.gitignore", + "tests/unit/gapic/dialogflow_v2/__init__.py", + "tests/unit/gapic/dialogflow_v2/test_agents.py", + "tests/unit/gapic/dialogflow_v2/test_answer_records.py", + "tests/unit/gapic/dialogflow_v2/test_contexts.py", + "tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py", + "tests/unit/gapic/dialogflow_v2/test_conversations.py", + "tests/unit/gapic/dialogflow_v2/test_documents.py", + "tests/unit/gapic/dialogflow_v2/test_entity_types.py", + "tests/unit/gapic/dialogflow_v2/test_environments.py", + "tests/unit/gapic/dialogflow_v2/test_intents.py", + "tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py", + "tests/unit/gapic/dialogflow_v2/test_participants.py", + "tests/unit/gapic/dialogflow_v2/test_session_entity_types.py", + "tests/unit/gapic/dialogflow_v2/test_sessions.py", + "tests/unit/gapic/dialogflow_v2beta1/__init__.py", + "tests/unit/gapic/dialogflow_v2beta1/test_agents.py", + "tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py", + "tests/unit/gapic/dialogflow_v2beta1/test_contexts.py", + "tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py", + "tests/unit/gapic/dialogflow_v2beta1/test_conversations.py", + "tests/unit/gapic/dialogflow_v2beta1/test_documents.py", + "tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py", + "tests/unit/gapic/dialogflow_v2beta1/test_environments.py", + "tests/unit/gapic/dialogflow_v2beta1/test_intents.py", + "tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py", + "tests/unit/gapic/dialogflow_v2beta1/test_participants.py", + "tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py", + "tests/unit/gapic/dialogflow_v2beta1/test_sessions.py" ] } \ No newline at end of file From 0a8cfb9ac71870df9f69ae518e32a920d08bd170 Mon Sep 17 00:00:00 2001 From: rogers140 Date: Thu, 25 Mar 2021 11:17:23 -0700 Subject: [PATCH 2/5] docs(samples): add Agent Assist code samples (#267) --- samples/snippets/answer_record_management.py | 49 ++++ .../snippets/answer_record_management_test.py | 97 ++++++++ samples/snippets/conversation_management.py | 93 ++++++++ .../conversation_profile_management.py | 221 ++++++++++++++++++ .../conversation_profile_management_test.py | 67 ++++++ samples/snippets/create_document_test.py | 25 +- samples/snippets/document_management.py | 203 +++++++++++----- samples/snippets/knowledge_base_management.py | 103 ++++++-- samples/snippets/participant_management.py | 103 ++++++++ .../snippets/participant_management_test.py | 144 ++++++++++++ samples/snippets/requirements.txt | 2 +- 11 files changed, 1017 insertions(+), 90 deletions(-) create mode 100644 samples/snippets/answer_record_management.py create mode 100644 samples/snippets/answer_record_management_test.py create mode 100644 samples/snippets/conversation_management.py create mode 100644 samples/snippets/conversation_profile_management.py create mode 100644 samples/snippets/conversation_profile_management_test.py create mode 100644 samples/snippets/participant_management.py create mode 100644 samples/snippets/participant_management_test.py diff --git a/samples/snippets/answer_record_management.py b/samples/snippets/answer_record_management.py new file mode 100644 index 000000000..dd5690dd6 --- /dev/null +++ b/samples/snippets/answer_record_management.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +# Copyright 2021 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. +"""Dialogflow API Python sample showing how to manage AnswerRecord. +""" + +from google.cloud import dialogflow_v2beta1 as dialogflow + + +# [START dialogflow_update_answer_record] +def update_answer_record(project_id, answer_record_id, is_clicked): + """Update the answer record. + + Args: + project_id: The GCP project linked with the conversation profile. + answer_record_id: The answer record id returned along with the + suggestion. + is_clicked: whether the answer record is clicked.""" + + client = dialogflow.AnswerRecordsClient() + answer_record_path = client.answer_record_path(project_id, + answer_record_id) + + response = client.update_answer_record( + answer_record={ + 'name': answer_record_path, + 'answer_feedback': { + 'clicked': is_clicked + } + }, + update_mask={'paths': ['answer_feedback']}) + print('AnswerRecord Name: {}'.format(response.name)) + print('Clicked: {}'.format(response.answer_feedback.clicked)) + return response + + +# [END dialogflow_update_answer_record] diff --git a/samples/snippets/answer_record_management_test.py b/samples/snippets/answer_record_management_test.py new file mode 100644 index 000000000..b72b479e7 --- /dev/null +++ b/samples/snippets/answer_record_management_test.py @@ -0,0 +1,97 @@ +# Copyright 2021 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 os + +import answer_record_management +import conversation_management +import conversation_profile_management +import participant_management + +PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') +SMART_REPLY_MODEL = os.getenv('SMART_REPLY_MODEL') +SMART_REPLY_ALLOWLIST = os.getenv('SMART_REPLY_ALLOWLIST') +CONVERSATION_PROFILE_DISPLAY_NAME = 'sample code profile for smart reply' + + +def test_smart_reply(capsys): + """Test smart reply feature. + """ + + # Create conversation profile. + conversation_profile_management.create_conversation_profile_smart_reply( + project_id=PROJECT_ID, + display_name=CONVERSATION_PROFILE_DISPLAY_NAME, + smart_reply_allowlist_name=SMART_REPLY_ALLOWLIST, + smart_reply_model_name=SMART_REPLY_MODEL) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(CONVERSATION_PROFILE_DISPLAY_NAME) in out + conversation_profile_id = out.split('conversationProfiles/')[1].rstrip() + + # Create conversation. + conversation_management.create_conversation( + project_id=PROJECT_ID, conversation_profile_id=conversation_profile_id) + + out, _ = capsys.readouterr() + conversation_id = out.split('conversations/')[1].rstrip() + + # Create end user participant. + participant_management.create_participant(project_id=PROJECT_ID, + conversation_id=conversation_id, + role='END_USER') + out, _ = capsys.readouterr() + end_user_id = out.split('participants/')[1].rstrip() + + # Create human agent participant. + participant_management.create_participant(project_id=PROJECT_ID, + conversation_id=conversation_id, + role='HUMAN_AGENT') + out, _ = capsys.readouterr() + human_agent_id = out.split('participants/')[1].rstrip() + + # AnalyzeContent + participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=human_agent_id, + text='Hi, how are you?') + out, _ = capsys.readouterr() + assert 'What would you like to know?' in out + + response = participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=end_user_id, + text='I am doing well, just want to check') + out, _ = capsys.readouterr() + assert 'Sounds good.' in out + # Update AnswerRecord. + answer_record_id = response.human_agent_suggestion_results[ + 0].suggest_smart_replies_response.smart_reply_answers[ + 0].answer_record.split('answerRecords/')[1].rstrip() + answer_record_management.update_answer_record( + project_id=PROJECT_ID, + answer_record_id=answer_record_id, + is_clicked=True) + out, _ = capsys.readouterr() + assert 'Clicked: True' in out + + # Complete conversation. + conversation_management.complete_conversation( + project_id=PROJECT_ID, conversation_id=conversation_id) + + # Delete conversation profile. + conversation_profile_management.delete_conversation_profile( + project_id=PROJECT_ID, conversation_profile_id=conversation_profile_id) diff --git a/samples/snippets/conversation_management.py b/samples/snippets/conversation_management.py new file mode 100644 index 000000000..e6c734929 --- /dev/null +++ b/samples/snippets/conversation_management.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python + +# Copyright 2021 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. +"""Dialogflow API Python sample showing how to manage Conversations. +""" + +from google.cloud import dialogflow_v2beta1 as dialogflow + + +# [START dialogflow_create_conversation] +def create_conversation(project_id, conversation_profile_id): + """Creates a conversation with given values + + Args: + project_id: The GCP project linked with the conversation. + conversation_profile_id: The conversation profile id used to create + conversation.""" + + client = dialogflow.ConversationsClient() + conversation_profile_client = dialogflow.ConversationProfilesClient() + project_path = client.common_project_path(project_id) + conversation_profile_path = ( + conversation_profile_client.conversation_profile_path( + project_id, conversation_profile_id)) + conversation = {'conversation_profile': conversation_profile_path} + response = client.create_conversation(parent=project_path, + conversation=conversation) + + print('Life Cycle State: {}'.format(response.lifecycle_state)) + print('Conversation Profile Name: {}'.format( + response.conversation_profile)) + print('Name: {}'.format(response.name)) + return response + + +# [END dialogflow_create_conversation] + + +# [START dialogflow_get_conversation] +def get_conversation(project_id, conversation_id): + """Gets a specific conversation profile. + + Args: + project_id: The GCP project linked with the conversation. + conversation_id: Id of the conversation.""" + + client = dialogflow.ConversationsClient() + conversation_path = client.conversation_path(project_id, conversation_id) + + response = client.get_conversation(name=conversation_path) + + print('Life Cycle State: {}'.format(response.lifecycle_state)) + print('Conversation Profile Name: {}'.format( + response.conversation_profile)) + print('Name: {}'.format(response.name)) + return response + + +# [END dialogflow_get_conversation] + + +# [START dialogflow_complete_conversation] +def complete_conversation(project_id, conversation_id): + """Completes the specified conversation. Finished conversations are purged from the database after 30 days. + + Args: + project_id: The GCP project linked with the conversation. + conversation_id: Id of the conversation.""" + + client = dialogflow.ConversationsClient() + conversation_path = client.conversation_path(project_id, conversation_id) + conversation = client.complete_conversation(name=conversation_path) + print('Completed Conversation.') + print('Life Cycle State: {}'.format(conversation.lifecycle_state)) + print('Conversation Profile Name: {}'.format( + conversation.conversation_profile)) + print('Name: {}'.format(conversation.name)) + return conversation + + +# [END dialogflow_complete_conversation] diff --git a/samples/snippets/conversation_profile_management.py b/samples/snippets/conversation_profile_management.py new file mode 100644 index 000000000..22ae1d384 --- /dev/null +++ b/samples/snippets/conversation_profile_management.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python + +# Copyright 2021 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. +"""Dialogflow API Python sample showing how to manage Conversation Profiles. +""" + +from google.cloud import dialogflow_v2beta1 as dialogflow + + +# [START dialogflow_list_conversation_profiles] +def list_conversation_profiles(project_id): + """Lists the conversation profiles belonging to a project. + + Args: project_id: The GCP project linked with the conversation profile.""" + + client = dialogflow.ConversationProfilesClient() + project_path = client.common_project_path(project_id) + response = client.list_conversation_profiles(parent=project_path) + for conversation_profile in response: + print('Display Name: {}'.format(conversation_profile.display_name)) + print('Name: {}'.format(conversation_profile.name)) + return response + + +# [END dialogflow_list_conversation_profiles] + + +# [START dialogflow_create_conversation_profile_article_faq] +def create_conversation_profile_article_faq( + project_id, + display_name, + article_suggestion_knowledge_base_id=None, + faq_knowledge_base_id=None): + """Creates a conversation profile with given values + + Args: project_id: The GCP project linked with the conversation profile. + display_name: The display name for the conversation profile to be + created. + article_suggestion_knowledge_base_id: knowledge base id for article + suggestion. + faq_knowledge_base_id: knowledge base id for faq.""" + + client = dialogflow.ConversationProfilesClient() + project_path = client.common_project_path(project_id) + + conversation_profile = { + 'display_name': display_name, + 'human_agent_assistant_config': { + 'human_agent_suggestion_config': { + 'feature_configs': [] + } + }, + 'language_code': 'en-US' + } + + if article_suggestion_knowledge_base_id is not None: + as_kb_path = dialogflow.KnowledgeBasesClient.knowledge_base_path( + project_id, article_suggestion_knowledge_base_id) + feature_config = { + 'suggestion_feature': { + 'type_': 'ARTICLE_SUGGESTION' + }, + 'suggestion_trigger_settings': { + 'no_small_talk': True, + 'only_end_user': True, + }, + 'query_config': { + 'knowledge_base_query_source': { + 'knowledge_bases': [as_kb_path] + }, + 'max_results': 3 + }, + } + conversation_profile['human_agent_assistant_config'][ + 'human_agent_suggestion_config']['feature_configs'].append( + feature_config) + if faq_knowledge_base_id is not None: + faq_kb_path = dialogflow.KnowledgeBasesClient.knowledge_base_path( + project_id, faq_knowledge_base_id) + feature_config = { + 'suggestion_feature': { + 'type_': 'FAQ' + }, + 'suggestion_trigger_settings': { + 'no_small_talk': True, + 'only_end_user': True, + }, + 'query_config': { + 'knowledge_base_query_source': { + 'knowledge_bases': [faq_kb_path] + }, + 'max_results': 3 + }, + } + conversation_profile['human_agent_assistant_config'][ + 'human_agent_suggestion_config']['feature_configs'].append( + feature_config) + + response = client.create_conversation_profile( + parent=project_path, conversation_profile=conversation_profile) + + print('Conversation Profile created:') + print('Display Name: {}'.format(response.display_name)) + # Put Name is the last to make it easier to retrieve. + print('Name: {}'.format(response.name)) + return response + + +# [END dialogflow_create_conversation_profile_article_faq] + + +# [START dialogflow_create_conversation_profile_smart_reply] +def create_conversation_profile_smart_reply(project_id, display_name, + smart_reply_allowlist_name, + smart_reply_model_name): + """Creates a conversation profile with given values for smart reply + + Args: project_id: The GCP project linked with the conversation profile. + display_name: The display name for the conversation profile to be + created. + smart_reply_allowlist_name: document name for smart reply allowlist. + smart_reply_model_name: conversation model name for smart reply.""" + + client = dialogflow.ConversationProfilesClient() + project_path = client.common_project_path(project_id) + + conversation_profile = { + 'display_name': display_name, + 'human_agent_assistant_config': { + 'human_agent_suggestion_config': { + 'feature_configs': [] + } + }, + 'language_code': 'en-US' + } + feature_config = { + 'suggestion_feature': { + 'type_': 'SMART_REPLY' + }, + 'suggestion_trigger_settings': { + 'no_small_talk': True, + 'only_end_user': True, + }, + 'query_config': { + 'document_query_source': { + 'documents': [smart_reply_allowlist_name] + }, + 'max_results': 3 + }, + 'conversation_model_config': { + 'model': smart_reply_model_name + } + } + conversation_profile['human_agent_assistant_config'][ + 'human_agent_suggestion_config']['feature_configs'].append( + feature_config) + + response = client.create_conversation_profile( + parent=project_path, conversation_profile=conversation_profile) + + print('Conversation Profile created:') + print('Display Name: {}'.format(response.display_name)) + # Put Name is the last to make it easier to retrieve. + print('Name: {}'.format(response.name)) + return response + + +# [END dialogflow_create_conversation_profile_smart_reply] + + +# [START dialogflow_get_conversation_profile] +def get_conversation_profile(project_id, conversation_profile_id): + """Gets a specific conversation profile. + + Args: project_id: The GCP project linked with the conversation profile. + conversation_profile_id: Id of the conversation profile.""" + + client = dialogflow.ConversationProfilesClient() + conversation_profile_path = client.conversation_profile_path( + project_id, conversation_profile_id) + + response = client.get_conversation_profile(name=conversation_profile_path) + + print('Got conversation profile:') + print('Display Name: {}'.format(response.display_name)) + print('Name: {}'.format(response.name)) + return response + + +# [END dialogflow_get_conversation_profile] + + +# [START dialogflow_delete_conversation_profile] +def delete_conversation_profile(project_id, conversation_profile_id): + """Deletes a specific conversation profile. + + Args: project_id: The GCP project linked with the conversation profile. + conversation_profile_id: Id of the conversation profile.""" + + client = dialogflow.ConversationProfilesClient() + conversation_profile_path = client.conversation_profile_path( + project_id, conversation_profile_id) + + client.delete_conversation_profile(name=conversation_profile_path) + + print('Conversation Profile deleted.') + + +# [END dialogflow_delete_conversation_profile] diff --git a/samples/snippets/conversation_profile_management_test.py b/samples/snippets/conversation_profile_management_test.py new file mode 100644 index 000000000..0347a8b34 --- /dev/null +++ b/samples/snippets/conversation_profile_management_test.py @@ -0,0 +1,67 @@ +# Copyright 2021 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 absolute_import + +import os + +import conversation_profile_management + +PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') + +CONVERSATION_PROFILE_DISPLAY_NAME = 'fake_conversation_profile_name' + + +def test_create_conversation_profile(capsys): + # Check the conversation profile does not yet exists. + conversation_profile_management.list_conversation_profiles(PROJECT_ID) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format( + CONVERSATION_PROFILE_DISPLAY_NAME) not in out + + # Create a conversation profile. + conversation_profile_management.create_conversation_profile_article_faq( + project_id=PROJECT_ID, display_name=CONVERSATION_PROFILE_DISPLAY_NAME, + article_suggestion_knowledge_base_id='abc') + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format( + CONVERSATION_PROFILE_DISPLAY_NAME) in out + + conversation_profile_id = out.split('conversationProfiles/')[1].rstrip() + + # List conversation profiles. + conversation_profile_management.list_conversation_profiles(PROJECT_ID) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format( + CONVERSATION_PROFILE_DISPLAY_NAME) in out + + # Get the conversation profile. + conversation_profile_management.get_conversation_profile( + PROJECT_ID, conversation_profile_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(CONVERSATION_PROFILE_DISPLAY_NAME) in out + + # Delete the conversation profile. + conversation_profile_management.delete_conversation_profile( + PROJECT_ID, conversation_profile_id) + + # Verify the converstion profile is deleted. + conversation_profile_management.list_conversation_profiles(PROJECT_ID) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format( + CONVERSATION_PROFILE_DISPLAY_NAME) not in out diff --git a/samples/snippets/create_document_test.py b/samples/snippets/create_document_test.py index 337976c45..b65e577aa 100644 --- a/samples/snippets/create_document_test.py +++ b/samples/snippets/create_document_test.py @@ -17,7 +17,8 @@ import os import uuid -from google.cloud import dialogflow_v2beta1 +from google.cloud import dialogflow_v2beta1 as dialogflow + import pytest import document_management @@ -31,23 +32,21 @@ @pytest.fixture(scope="function", autouse=True) def setup_teardown(): # Create a knowledge base to use in document management - client = dialogflow_v2beta1.KnowledgeBasesClient() + client = dialogflow.KnowledgeBasesClient() project_path = client.common_project_path(PROJECT_ID) - knowledge_base = dialogflow_v2beta1.KnowledgeBase(display_name=KNOWLEDGE_BASE_NAME) - response = client.create_knowledge_base( - parent=project_path, knowledge_base=knowledge_base - ) - pytest.KNOWLEDGE_BASE_ID = response.name.split("/knowledgeBases/")[1].split("\n")[0] + knowledge_base = dialogflow.KnowledgeBase(display_name=KNOWLEDGE_BASE_NAME) + response = client.create_knowledge_base(parent=project_path, + knowledge_base=knowledge_base) + pytest.KNOWLEDGE_BASE_ID = response.name.split( + "/knowledgeBases/")[1].split("\n")[0] yield # Delete the created knowledge base - knowledge_base_path = client.knowledge_base_path( - PROJECT_ID, pytest.KNOWLEDGE_BASE_ID - ) - request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest( - name=knowledge_base_path, force=True - ) + knowledge_base_path = client.knowledge_base_path(PROJECT_ID, + pytest.KNOWLEDGE_BASE_ID) + request = dialogflow.DeleteKnowledgeBaseRequest(name=knowledge_base_path, + force=True) client.delete_knowledge_base(request=request) diff --git a/samples/snippets/document_management.py b/samples/snippets/document_management.py index 4cbd8a346..b08ddf752 100644 --- a/samples/snippets/document_management.py +++ b/samples/snippets/document_management.py @@ -20,21 +20,54 @@ python document_management.py -h python document_management.py --project-id PROJECT_ID \ --knowledge-base-id knowledge_base_id \ + list + python document_management.py --project-id PROJECT_ID \ + --knowledge-base-id knowledge_base_id \ create --display-name DISPLAY_NAME --mime-type MIME_TYPE \ --knowledge-type KNOWLEDGE_TYPE --content-uri CONTENT_URI python document_management.py --project-id PROJECT_ID \ --knowledge-base-id knowledge_base_id \ + get --document-id DOCUMENT_ID + python document_management.py --project-id PROJECT_ID \ + --knowledge-base-id knowledge_base_id \ + delete --document-id DOCUMENT_ID """ import argparse -KNOWLEDGE_TYPES = ["KNOWLEDGE_TYPE_UNSPECIFIED", "FAQ", "EXTRACTIVE_QA"] + +KNOWLEDGE_TYPES = ['KNOWLEDGE_TYPE_UNSPECIFIED', 'FAQ', 'EXTRACTIVE_QA', 'ARTICLE_SUGGESTION'] + + +# [START dialogflow_list_document] +def list_documents(project_id, knowledge_base_id): + """Lists the Documents belonging to a Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base.""" + from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path( + project_id, knowledge_base_id) + + print('Documents for Knowledge Id: {}'.format(knowledge_base_id)) + response = client.list_documents(parent=knowledge_base_path) + for document in response: + print(' - Display Name: {}'.format(document.display_name)) + print(' - Knowledge ID: {}'.format(document.name)) + print(' - MIME Type: {}'.format(document.mime_type)) + print(' - Knowledge Types:') + for knowledge_type in document.knowledge_types: + print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) + print(' - Source: {}\n'.format(document.content_uri)) + return response +# [END dialogflow_list_document] # [START dialogflow_create_document]] -def create_document( - project_id, knowledge_base_id, display_name, mime_type, knowledge_type, content_uri -): +def create_document(project_id, knowledge_base_id, display_name, mime_type, + knowledge_type, content_uri): """Creates a Document. Args: @@ -48,84 +81,140 @@ def create_document( content_uri: Uri of the document, e.g. gs://path/mydoc.csv, http://mypage.com/faq.html.""" from google.cloud import dialogflow_v2beta1 as dialogflow - client = dialogflow.DocumentsClient() knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path( - project_id, knowledge_base_id - ) + project_id, knowledge_base_id) document = dialogflow.Document( - display_name=display_name, mime_type=mime_type, content_uri=content_uri - ) + display_name=display_name, mime_type=mime_type, + content_uri=content_uri) document.knowledge_types.append( getattr(dialogflow.Document.KnowledgeType, knowledge_type) ) response = client.create_document(parent=knowledge_base_path, document=document) - print("Waiting for results...") + print('Waiting for results...') document = response.result(timeout=120) - print("Created Document:") - print(" - Display Name: {}".format(document.display_name)) - print(" - Knowledge ID: {}".format(document.name)) - print(" - MIME Type: {}".format(document.mime_type)) - print(" - Knowledge Types:") + print('Created Document:') + print(' - Display Name: {}'.format(document.display_name)) + print(' - Knowledge ID: {}'.format(document.name)) + print(' - MIME Type: {}'.format(document.mime_type)) + print(' - Knowledge Types:') for knowledge_type in document.knowledge_types: - print(" - {}".format(KNOWLEDGE_TYPES[knowledge_type])) - print(" - Source: {}\n".format(document.content_uri)) + print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) + print(' - Source: {}\n'.format(document.content_uri)) +# [END dialogflow_create_document] + + +# [START dialogflow_get_document]] +def get_document(project_id, knowledge_base_id, document_id): + """Gets a Document. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base. + document_id: Id of the Document.""" + from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + document_path = client.document_path(project_id, knowledge_base_id, + document_id) + + response = client.get_document(name=document_path) + print('Got Document:') + print(' - Display Name: {}'.format(response.display_name)) + print(' - Knowledge ID: {}'.format(response.name)) + print(' - MIME Type: {}'.format(response.mime_type)) + print(' - Knowledge Types:') + for knowledge_type in response.knowledge_types: + print(' - {}'.format(KNOWLEDGE_TYPES[knowledge_type])) + print(' - Source: {}\n'.format(response.content_uri)) + return response +# [END dialogflow_get_document]] + + +# [START dialogflow_delete_document]] +def delete_document(project_id, knowledge_base_id, document_id): + """Deletes a Document. + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base. + document_id: Id of the Document.""" + from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.DocumentsClient() + document_path = client.document_path(project_id, knowledge_base_id, + document_id) -# [END dialogflow_create_document]] + response = client.delete_document(name=document_path) + print('operation running:\n {}'.format(response.operation)) + print('Waiting for results...') + print('Done.\n {}'.format(response.result())) +# [END dialogflow_delete_document]] -if __name__ == "__main__": +if __name__ == '__main__': parser = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - parser.add_argument("--project-id", help="Project id. Required.", required=True) + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( - "--knowledge-base-id", - help="The id of the Knowledge Base that the Document belongs to", - required=True, - ) + '--project-id', help='Project id. Required.', required=True) + parser.add_argument( + '--knowledge-base-id', + help='The id of the Knowledge Base that the Document belongs to', + required=True) - subparsers = parser.add_subparsers(dest="command") + subparsers = parser.add_subparsers(dest='command') + + list_parser = subparsers.add_parser( + 'list', + help='List all Documents that belong to a certain Knowledge base.') create_parser = subparsers.add_parser( - "create", help="Create a Document for a certain Knowledge base." - ) + 'create', help='Create a Document for a certain Knowledge base.') create_parser.add_argument( - "--display-name", - help="A name of the Document, mainly used for display purpose, " - "can not be used to identify the Document.", - default=str(""), - ) + '--display-name', + help='A name of the Document, mainly used for display purpose, ' + 'can not be used to identify the Document.', + default=str('')) create_parser.add_argument( - "--mime-type", - help="The mime-type of the Document, e.g. text/csv, text/html, " - "text/plain, text/pdf etc. ", - required=True, - ) + '--mime-type', + help='The mime-type of the Document, e.g. text/csv, text/html, ' + 'text/plain, text/pdf etc. ', + required=True) create_parser.add_argument( - "--knowledge-type", - help="The knowledge-type of the Document, e.g. FAQ, EXTRACTIVE_QA.", - required=True, - ) + '--knowledge-type', + help='The knowledge-type of the Document, e.g. FAQ, EXTRACTIVE_QA.', + required=True) create_parser.add_argument( - "--content-uri", - help="The uri of the Document, e.g. gs://path/mydoc.csv, " - "http://mypage.com/faq.html", - required=True, - ) + '--content-uri', + help='The uri of the Document, e.g. gs://path/mydoc.csv, ' + 'http://mypage.com/faq.html', + required=True) + + get_parser = subparsers.add_parser( + 'get', help='Get a Document by its id and the Knowledge base id.') + get_parser.add_argument( + '--document-id', help='The id of the Document', required=True) + + delete_parser = subparsers.add_parser( + 'delete', help='Delete a Document by its id and the Knowledge base' + 'id.') + delete_parser.add_argument( + '--document-id', + help='The id of the Document you want to delete', + required=True) args = parser.parse_args() - if args.command == "create": - create_document( - args.project_id, - args.knowledge_base_id, - args.display_name, - args.mime_type, - args.knowledge_type, - args.content_uri, - ) + if args.command == 'list': + list_documents(args.project_id, args.knowledge_base_id) + elif args.command == 'create': + create_document(args.project_id, args.knowledge_base_id, + args.display_name, args.mime_type, args.knowledge_type, + args.content_uri) + elif args.command == 'get': + get_document(args.project_id, args.knowledge_base_id, args.document_id) + elif args.command == 'delete': + delete_document(args.project_id, args.knowledge_base_id, + args.document_id) diff --git a/samples/snippets/knowledge_base_management.py b/samples/snippets/knowledge_base_management.py index 644a95f0e..d33044456 100644 --- a/samples/snippets/knowledge_base_management.py +++ b/samples/snippets/knowledge_base_management.py @@ -19,7 +19,13 @@ Examples: python knowledge_base_management.py -h python knowledge_base_management.py --project-id PROJECT_ID \ + list + python knowledge_base_management.py --project-id PROJECT_ID \ create --display-name DISPLAY_NAME + python knowledge_base_management.py --project-id PROJECT_ID \ + get --knowledge-base-id knowledge_base_id + python knowledge_base_management.py --project-id PROJECT_ID \ + delete --knowledge-base-id knowledge_base_id """ import argparse @@ -33,41 +39,100 @@ def create_knowledge_base(project_id, display_name): project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.""" from google.cloud import dialogflow_v2beta1 as dialogflow - client = dialogflow.KnowledgeBasesClient() project_path = client.common_project_path(project_id) - knowledge_base = dialogflow.KnowledgeBase(display_name=display_name) + knowledge_base = dialogflow.KnowledgeBase( + display_name=display_name) response = client.create_knowledge_base( - parent=project_path, knowledge_base=knowledge_base + parent=project_path, + knowledge_base=knowledge_base ) - print("Knowledge Base created:\n") - print("Display Name: {}\n".format(response.display_name)) - print("Knowledge ID: {}\n".format(response.name)) + print('Knowledge Base created:\n') + print('Display Name: {}\n'.format(response.display_name)) + print('Knowledge ID: {}\n'.format(response.name)) +# [END dialogflow_create_knowledge_base] -# [END dialogflow_create_knowledge_base] +# [START dialogflow_get_knowledge_base] +def get_knowledge_base(project_id, knowledge_base_id): + """Gets a specific Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base.""" + from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() + knowledge_base_path = client.knowledge_base_path( + project_id, knowledge_base_id) + + response = client.get_knowledge_base(name=knowledge_base_path) + + print('Got Knowledge Base:') + print(' - Display Name: {}'.format(response.display_name)) + print(' - Knowledge ID: {}'.format(response.name)) + return response +# [END dialogflow_get_knowledge_base] -if __name__ == "__main__": +# [START dialogflow_delete_knowledge_base] +def delete_knowledge_base(project_id, knowledge_base_id): + """Deletes a specific Knowledge base. + + Args: + project_id: The GCP project linked with the agent. + knowledge_base_id: Id of the Knowledge base.""" + from google.cloud import dialogflow_v2beta1 as dialogflow + client = dialogflow.KnowledgeBasesClient() + knowledge_base_path = client.knowledge_base_path( + project_id, knowledge_base_id) + + client.delete_knowledge_base(name=knowledge_base_path) + + print('Knowledge Base deleted.') +# [END dialogflow_delete_knowledge_base] + + +if __name__ == '__main__': parser = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - parser.add_argument("--project-id", help="Project/agent id.", required=True) + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument( + '--project-id', help='Project/agent id.', required=True) + + subparsers = parser.add_subparsers(dest='command') - subparsers = parser.add_subparsers(dest="command") + list_parser = subparsers.add_parser( + 'list', help='List all Knowledge bases that belong to the project.') - create_parser = subparsers.add_parser("create", help="Create a new Knowledge base.") + create_parser = subparsers.add_parser( + 'create', help='Create a new Knowledge base.') create_parser.add_argument( - "--display-name", - help="A name of the Knowledge base, used for display purpose, " - "can not be used to identify the Knowledge base.", - default=str(""), - ) + '--display-name', + help='A name of the Knowledge base, used for display purpose, ' + 'can not be used to identify the Knowledge base.', + default=str('')) + + get_parser = subparsers.add_parser( + 'get', help='Get a Knowledge base by its id.') + get_parser.add_argument( + '--knowledge-base-id', help='The id of the Knowledge base.', + required=True) + + delete_parser = subparsers.add_parser( + 'delete', help='Delete a Knowledge base by its id.') + delete_parser.add_argument( + '--knowledge-base-id', + help='The id of the Knowledge base you want to delete.', + required=True) args = parser.parse_args() - if args.command == "create": + if args.command == 'create': create_knowledge_base(args.project_id, args.display_name) + elif args.command == 'get': + get_knowledge_base(args.project_id, args.knowledge_base_id) + elif args.command == 'delete': + delete_knowledge_base(args.project_id, args.knowledge_base_id) diff --git a/samples/snippets/participant_management.py b/samples/snippets/participant_management.py new file mode 100644 index 000000000..f04b4c716 --- /dev/null +++ b/samples/snippets/participant_management.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python + +# Copyright 2021 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. +"""Dialogflow API Python sample showing how to manage Participants. +""" + +from google.cloud import dialogflow_v2beta1 as dialogflow + +ROLES = ['HUMAN_AGENT', 'AUTOMATED_AGENT', 'END_USER'] + + +# [START dialogflow_create_participant] +def create_participant(project_id, conversation_id, role): + """Creates a participant in a given conversation. + + Args: + project_id: The GCP project linked with the conversation profile. + conversation_id: Id of the conversation. + participant: participant to be created.""" + + client = dialogflow.ParticipantsClient() + conversation_path = dialogflow.ConversationsClient.conversation_path( + project_id, conversation_id) + if role in ROLES: + response = client.create_participant(parent=conversation_path, + participant={'role': role}) + print('Participant Created.') + print('Role: {}'.format(response.role)) + print('Name: {}'.format(response.name)) + + return response + + +# [END dialogflow_create_participant] + + +# [START dialogflow_analyze_content_text] +def analyze_content_text(project_id, conversation_id, participant_id, text): + """Analyze text message content from a participant. + + Args: + project_id: The GCP project linked with the conversation profile. + conversation_id: Id of the conversation. + participant_id: Id of the participant. + text: the text message that participant typed.""" + + client = dialogflow.ParticipantsClient() + participant_path = client.participant_path(project_id, conversation_id, + participant_id) + text_input = {'text': text, 'language_code': 'en-US'} + response = client.analyze_content(participant=participant_path, + text_input=text_input) + print('AnalyzeContent Response:') + print('Reply Text: {}'.format(response.reply_text)) + + for suggestion_result in response.human_agent_suggestion_results: + if suggestion_result.error is not None: + print('Error: {}'.format(suggestion_result.error.message)) + if suggestion_result.suggest_articles_response: + for answer in suggestion_result.suggest_articles_response.article_answers: + print('Article Suggestion Answer: {}'.format(answer.title)) + print('Answer Record: {}'.format(answer.answer_record)) + if suggestion_result.suggest_faq_answers_response: + for answer in suggestion_result.suggest_faq_answers_response.faq_answers: + print('Faq Answer: {}'.format(answer.answer)) + print('Answer Record: {}'.format(answer.answer_record)) + if suggestion_result.suggest_smart_replies_response: + for answer in suggestion_result.suggest_smart_replies_response.smart_reply_answers: + print('Smart Reply: {}'.format(answer.reply)) + print('Answer Record: {}'.format(answer.answer_record)) + + for suggestion_result in response.end_user_suggestion_results: + if suggestion_result.error: + print('Error: {}'.format(suggestion_result.error.message)) + if suggestion_result.suggest_articles_response: + for answer in suggestion_result.suggest_articles_response.article_answers: + print('Article Suggestion Answer: {}'.format(answer.title)) + print('Answer Record: {}'.format(answer.answer_record)) + if suggestion_result.suggest_faq_answers_response: + for answer in suggestion_result.suggest_faq_answers_response.faq_answers: + print('Faq Answer: {}'.format(answer.answer)) + print('Answer Record: {}'.format(answer.answer_record)) + if suggestion_result.suggest_smart_replies_response: + for answer in suggestion_result.suggest_smart_replies_response.smart_reply_answers: + print('Smart Reply: {}'.format(answer.reply)) + print('Answer Record: {}'.format(answer.answer_record)) + + return response + + +# [END dialogflow_analyze_content_text] diff --git a/samples/snippets/participant_management_test.py b/samples/snippets/participant_management_test.py new file mode 100644 index 000000000..b2a0563ff --- /dev/null +++ b/samples/snippets/participant_management_test.py @@ -0,0 +1,144 @@ +# Copyright 2021 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 os + +import conversation_management +import conversation_profile_management +import document_management +import knowledge_base_management +import participant_management + +PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT') +KNOWLEDGE_BASE_DISPLAY_NAME = 'fake_KNOWLEDGE_BASE_DISPLAY_NAME' +DOCUMENT_DISPLAY_NAME = 'Cancel an order' +CONVERSATION_PROFILE_DISPLAY_NAME = 'fake_conversation_profile' + + +def test_analyze_content_text(capsys): + """Test analyze content api with text only messages. + """ + # Create knowledge base. + knowledge_base_management.create_knowledge_base( + PROJECT_ID, KNOWLEDGE_BASE_DISPLAY_NAME) + out, _ = capsys.readouterr() + knowledge_base_id = out.split('knowledgeBases/')[1].rstrip() + # Get the knowledge base + knowledge_base_management.get_knowledge_base(PROJECT_ID, knowledge_base_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(KNOWLEDGE_BASE_DISPLAY_NAME) in out + + # Create documents. Note that you should get read permission of bucket gs://ruogu/parsed_5_24/7157212.html + # via Pantheon for service account (google application credential account) from here: + # https://pantheon.corp.google.com/storage/browser/ruogu/parsed_5_24/?project=agent-assistant-demo + document_management.create_document(PROJECT_ID, knowledge_base_id, + DOCUMENT_DISPLAY_NAME, 'text/html', + 'ARTICLE_SUGGESTION', + 'gs://ruogu/parsed_5_24/7157212.html') + out, _ = capsys.readouterr() + document_id = out.split('documents/')[1].split(' - MIME Type:')[0].rstrip() + + # Get the Document + document_management.get_document(PROJECT_ID, knowledge_base_id, + document_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(DOCUMENT_DISPLAY_NAME) in out + + # Create conversation profile. + conversation_profile_management.create_conversation_profile_article_faq( + project_id=PROJECT_ID, + display_name=CONVERSATION_PROFILE_DISPLAY_NAME, + article_suggestion_knowledge_base_id=knowledge_base_id) + + out, _ = capsys.readouterr() + assert 'Display Name: {}'.format(CONVERSATION_PROFILE_DISPLAY_NAME) in out + conversation_profile_id = out.split('conversationProfiles/')[1].rstrip() + + # Create conversation. + conversation_management.create_conversation( + project_id=PROJECT_ID, conversation_profile_id=conversation_profile_id) + + out, _ = capsys.readouterr() + conversation_id = out.split('conversations/')[1].rstrip() + + # Create end user participant. + participant_management.create_participant(project_id=PROJECT_ID, + conversation_id=conversation_id, + role='END_USER') + out, _ = capsys.readouterr() + end_user_id = out.split('participants/')[1].rstrip() + + # Create human agent participant. + participant_management.create_participant(project_id=PROJECT_ID, + conversation_id=conversation_id, + role='HUMAN_AGENT') + out, _ = capsys.readouterr() + human_agent_id = out.split('participants/')[1].rstrip() + + # AnalyzeContent + participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=human_agent_id, + text='Hi, how are you?') + out, _ = capsys.readouterr() + + participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=end_user_id, + text='Hi, I am doing well, how about you?') + out, _ = capsys.readouterr() + + participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=human_agent_id, + text='Great. How can I help you?') + out, _ = capsys.readouterr() + + participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=end_user_id, + text='So I ordered something, but I do not like it.') + out, _ = capsys.readouterr() + + participant_management.analyze_content_text( + project_id=PROJECT_ID, + conversation_id=conversation_id, + participant_id=end_user_id, + text='Thinking if I can cancel that order') + suggestion_out, _ = capsys.readouterr() + # Currently suggestion_out won't contain the suggestion we want since it + # takes time for document to be ready to serve. + # assert 'Cancel an order' in suggestion_out + + # Complete conversation. + conversation_management.complete_conversation( + project_id=PROJECT_ID, conversation_id=conversation_id) + + # Delete conversation profile. + conversation_profile_management.delete_conversation_profile( + project_id=PROJECT_ID, conversation_profile_id=conversation_profile_id) + + # Delete document. + document_management.delete_document(PROJECT_ID, knowledge_base_id, + document_id) + + # Delete the Knowledge Base. + knowledge_base_management.delete_knowledge_base(PROJECT_ID, + knowledge_base_id) diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt index c250f5c85..79820d6bc 100644 --- a/samples/snippets/requirements.txt +++ b/samples/snippets/requirements.txt @@ -1 +1 @@ -google-cloud-dialogflow==2.0.0 +google-cloud-dialogflow==2.1.0 From 31d1465a641f678c3345b6524362cfa49fdf71a2 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Tue, 30 Mar 2021 14:14:07 -0600 Subject: [PATCH 3/5] chore: add constraints file (#236) Add constraints file to test lower bounds --- testing/constraints-3.10.txt | 0 testing/constraints-3.11.txt | 0 testing/constraints-3.6.txt | 9 +++++++++ testing/constraints-3.7.txt | 0 testing/constraints-3.8.txt | 0 testing/constraints-3.9.txt | 0 6 files changed, 9 insertions(+) create mode 100644 testing/constraints-3.10.txt create mode 100644 testing/constraints-3.11.txt create mode 100644 testing/constraints-3.6.txt create mode 100644 testing/constraints-3.7.txt create mode 100644 testing/constraints-3.8.txt create mode 100644 testing/constraints-3.9.txt diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt new file mode 100644 index 000000000..e69de29bb diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt new file mode 100644 index 000000000..e69de29bb diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt new file mode 100644 index 000000000..04d54afee --- /dev/null +++ b/testing/constraints-3.6.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List *all* library dependencies and extras in this file. +# Pin the version to the lower bound. +# +# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", +# Then this file should have foo==1.14.0 +google-api-core==1.22.0 +proto-plus==1.10.0 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt new file mode 100644 index 000000000..e69de29bb diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt new file mode 100644 index 000000000..e69de29bb diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt new file mode 100644 index 000000000..e69de29bb From 06381fcc965669e1b3dc8bec22aa567dceb6f935 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Mon, 12 Apr 2021 12:25:07 -0700 Subject: [PATCH 4/5] fix: remove rpc or fields that are unintended to release (#264) fix: remove StreamingAnalyzeContent, CreateCallMatcher, ListCallMatchers, DeleteCallMatcher rpc from v2/v2beta1 fix: remove `input_audio` field from AnalyzeContentRequest from v2/v2beta1 fix: remove proto message CreateCallMatcherRequest, CreateCallMatcherResponse, ListCallMatchersRequest, ListCallMatchersResponse, DeleteCallMatcherRequest, DeleteCallMatcherResponse, CallMatcher, StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse, AudioInput from v2/v2beta1, TelephonyDtmfEvents, TelephonyDtmf from v2 fix: Remove resource_reference from UpdateAnswerRecord fix: remove resource_reference for invisible resources **NOTE**: This PR contains breaking changes (deletions) to the library surface. The Dialogflow API team has provided documentation indicating that there were a limited number of users. Those users have been allowlisted and will be able to continue to call those RPCs using a previous version of the library. --- .kokoro/samples/python3.6/periodic-head.cfg | 11 + .kokoro/samples/python3.7/periodic-head.cfg | 11 + .kokoro/samples/python3.8/periodic-head.cfg | 11 + .kokoro/test-samples-against-head.sh | 28 + .kokoro/test-samples-impl.sh | 102 ++ .kokoro/test-samples.sh | 96 +- .pre-commit-config.yaml | 2 +- google/cloud/dialogflow/__init__.py | 22 - google/cloud/dialogflow_v2/__init__.py | 26 +- google/cloud/dialogflow_v2/proto/agent.proto | 32 + .../dialogflow_v2/proto/answer_record.proto | 53 +- .../dialogflow_v2/proto/audio_config.proto | 79 +- .../cloud/dialogflow_v2/proto/context.proto | 40 + .../dialogflow_v2/proto/conversation.proto | 162 --- .../proto/conversation_profile.proto | 5 +- .../cloud/dialogflow_v2/proto/document.proto | 21 + .../dialogflow_v2/proto/entity_type.proto | 37 + .../dialogflow_v2/proto/environment.proto | 3 + google/cloud/dialogflow_v2/proto/intent.proto | 25 + .../dialogflow_v2/proto/knowledge_base.proto | 17 + .../dialogflow_v2/proto/participant.proto | 180 +--- .../cloud/dialogflow_v2/proto/session.proto | 8 + .../proto/session_entity_type.proto | 34 + .../services/agents/transports/base.py | 18 +- .../services/agents/transports/grpc.py | 103 +- .../agents/transports/grpc_asyncio.py | 111 +-- .../services/answer_records/async_client.py | 11 +- .../services/answer_records/client.py | 11 +- .../answer_records/transports/base.py | 18 +- .../answer_records/transports/grpc.py | 101 +- .../answer_records/transports/grpc_asyncio.py | 109 +-- .../services/contexts/transports/base.py | 18 +- .../services/contexts/transports/grpc.py | 101 +- .../contexts/transports/grpc_asyncio.py | 109 +-- .../conversation_profiles/transports/base.py | 18 +- .../conversation_profiles/transports/grpc.py | 101 +- .../transports/grpc_asyncio.py | 109 +-- .../services/conversations/async_client.py | 268 ----- .../services/conversations/client.py | 285 ------ .../services/conversations/pagers.py | 128 --- .../services/conversations/transports/base.py | 60 +- .../services/conversations/transports/grpc.py | 185 +--- .../conversations/transports/grpc_asyncio.py | 196 +--- .../services/documents/transports/base.py | 18 +- .../services/documents/transports/grpc.py | 103 +- .../documents/transports/grpc_asyncio.py | 111 +-- .../services/entity_types/transports/base.py | 18 +- .../services/entity_types/transports/grpc.py | 103 +- .../entity_types/transports/grpc_asyncio.py | 111 +-- .../services/environments/transports/base.py | 18 +- .../services/environments/transports/grpc.py | 101 +- .../environments/transports/grpc_asyncio.py | 109 +-- .../services/intents/transports/base.py | 18 +- .../services/intents/transports/grpc.py | 103 +- .../intents/transports/grpc_asyncio.py | 111 +-- .../knowledge_bases/transports/base.py | 18 +- .../knowledge_bases/transports/grpc.py | 101 +- .../transports/grpc_asyncio.py | 109 +-- .../services/participants/async_client.py | 131 +-- .../services/participants/client.py | 129 +-- .../services/participants/transports/base.py | 36 +- .../services/participants/transports/grpc.py | 149 +-- .../participants/transports/grpc_asyncio.py | 157 +-- .../session_entity_types/transports/base.py | 18 +- .../session_entity_types/transports/grpc.py | 101 +- .../transports/grpc_asyncio.py | 109 +-- .../services/sessions/async_client.py | 1 + .../services/sessions/transports/base.py | 19 +- .../services/sessions/transports/grpc.py | 101 +- .../sessions/transports/grpc_asyncio.py | 109 +-- google/cloud/dialogflow_v2/types/__init__.py | 22 - .../cloud/dialogflow_v2/types/audio_config.py | 38 +- .../cloud/dialogflow_v2/types/conversation.py | 164 ---- .../cloud/dialogflow_v2/types/participant.py | 250 +---- google/cloud/dialogflow_v2beta1/__init__.py | 22 +- .../proto/answer_record.proto | 54 +- .../proto/audio_config.proto | 6 + .../proto/conversation.proto | 239 +---- .../proto/conversation_profile.proto | 5 +- .../proto/participant.proto | 207 +--- .../dialogflow_v2beta1/proto/session.proto | 3 + .../services/agents/transports/base.py | 18 +- .../services/agents/transports/grpc.py | 103 +- .../agents/transports/grpc_asyncio.py | 111 +-- .../services/answer_records/async_client.py | 20 +- .../services/answer_records/client.py | 20 +- .../answer_records/transports/base.py | 18 +- .../answer_records/transports/grpc.py | 101 +- .../answer_records/transports/grpc_asyncio.py | 109 +-- .../services/contexts/transports/base.py | 18 +- .../services/contexts/transports/grpc.py | 101 +- .../contexts/transports/grpc_asyncio.py | 109 +-- .../conversation_profiles/transports/base.py | 18 +- .../conversation_profiles/transports/grpc.py | 101 +- .../transports/grpc_asyncio.py | 109 +-- .../services/conversations/async_client.py | 272 +----- .../services/conversations/client.py | 289 +----- .../services/conversations/pagers.py | 128 --- .../services/conversations/transports/base.py | 60 +- .../services/conversations/transports/grpc.py | 185 +--- .../conversations/transports/grpc_asyncio.py | 196 +--- .../services/documents/transports/base.py | 18 +- .../services/documents/transports/grpc.py | 103 +- .../documents/transports/grpc_asyncio.py | 111 +-- .../services/entity_types/transports/base.py | 18 +- .../services/entity_types/transports/grpc.py | 103 +- .../entity_types/transports/grpc_asyncio.py | 111 +-- .../services/environments/transports/base.py | 18 +- .../services/environments/transports/grpc.py | 101 +- .../environments/transports/grpc_asyncio.py | 109 +-- .../services/intents/transports/base.py | 18 +- .../services/intents/transports/grpc.py | 103 +- .../intents/transports/grpc_asyncio.py | 111 +-- .../knowledge_bases/transports/base.py | 18 +- .../knowledge_bases/transports/grpc.py | 101 +- .../transports/grpc_asyncio.py | 109 +-- .../services/participants/async_client.py | 132 +-- .../services/participants/client.py | 130 +-- .../services/participants/transports/base.py | 36 +- .../services/participants/transports/grpc.py | 146 +-- .../participants/transports/grpc_asyncio.py | 154 +-- .../session_entity_types/transports/base.py | 18 +- .../session_entity_types/transports/grpc.py | 101 +- .../transports/grpc_asyncio.py | 109 +-- .../services/sessions/async_client.py | 1 + .../services/sessions/transports/base.py | 19 +- .../services/sessions/transports/grpc.py | 101 +- .../sessions/transports/grpc_asyncio.py | 109 +-- .../dialogflow_v2beta1/types/__init__.py | 18 - .../dialogflow_v2beta1/types/audio_config.py | 2 + .../dialogflow_v2beta1/types/conversation.py | 165 ---- .../dialogflow_v2beta1/types/participant.py | 289 +----- .../cloud/dialogflow_v2beta1/types/session.py | 10 + noxfile.py | 31 +- renovate.json | 3 +- scripts/fixup_dialogflow_v2_keywords.py | 6 +- scripts/fixup_dialogflow_v2beta1_keywords.py | 6 +- setup.py | 2 +- synth.metadata | 435 +-------- synth.py | 6 +- testing/constraints-3.6.txt | 10 +- testing/constraints-3.7.txt | 2 + testing/constraints-3.8.txt | 2 + testing/constraints-3.9.txt | 2 + .../gapic/dialogflow_v2/test_conversations.py | 924 +----------------- .../gapic/dialogflow_v2/test_participants.py | 101 -- .../dialogflow_v2beta1/test_conversations.py | 924 +----------------- .../dialogflow_v2beta1/test_participants.py | 101 -- 148 files changed, 2997 insertions(+), 10623 deletions(-) create mode 100644 .kokoro/samples/python3.6/periodic-head.cfg create mode 100644 .kokoro/samples/python3.7/periodic-head.cfg create mode 100644 .kokoro/samples/python3.8/periodic-head.cfg create mode 100755 .kokoro/test-samples-against-head.sh create mode 100755 .kokoro/test-samples-impl.sh diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg new file mode 100644 index 000000000..f9cfcd33e --- /dev/null +++ b/.kokoro/samples/python3.6/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.7/periodic-head.cfg b/.kokoro/samples/python3.7/periodic-head.cfg new file mode 100644 index 000000000..f9cfcd33e --- /dev/null +++ b/.kokoro/samples/python3.7/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg new file mode 100644 index 000000000..f9cfcd33e --- /dev/null +++ b/.kokoro/samples/python3.8/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-pubsub/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/test-samples-against-head.sh b/.kokoro/test-samples-against-head.sh new file mode 100755 index 000000000..3187ad1e3 --- /dev/null +++ b/.kokoro/test-samples-against-head.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# Copyright 2020 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 +# +# https://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. + +# A customized test runner for samples. +# +# For periodic builds, you can specify this file for testing against head. + +# `-e` enables the script to automatically fail when a command fails +# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero +set -eo pipefail +# Enables `**` to include files nested inside sub-folders +shopt -s globstar + +cd github/python-dialogflow + +exec .kokoro/test-samples-impl.sh diff --git a/.kokoro/test-samples-impl.sh b/.kokoro/test-samples-impl.sh new file mode 100755 index 000000000..cf5de74c1 --- /dev/null +++ b/.kokoro/test-samples-impl.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# Copyright 2021 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 +# +# https://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. + + +# `-e` enables the script to automatically fail when a command fails +# `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero +set -eo pipefail +# Enables `**` to include files nested inside sub-folders +shopt -s globstar + +# Exit early if samples directory doesn't exist +if [ ! -d "./samples" ]; then + echo "No tests run. `./samples` not found" + exit 0 +fi + +# Disable buffering, so that the logs stream through. +export PYTHONUNBUFFERED=1 + +# Debug: show build environment +env | grep KOKORO + +# Install nox +python3.6 -m pip install --upgrade --quiet nox + +# Use secrets acessor service account to get secrets +if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then + gcloud auth activate-service-account \ + --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ + --project="cloud-devrel-kokoro-resources" +fi + +# This script will create 3 files: +# - testing/test-env.sh +# - testing/service-account.json +# - testing/client-secrets.json +./scripts/decrypt-secrets.sh + +source ./testing/test-env.sh +export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json + +# For cloud-run session, we activate the service account for gcloud sdk. +gcloud auth activate-service-account \ + --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" + +export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json + +echo -e "\n******************** TESTING PROJECTS ********************" + +# Switch to 'fail at end' to allow all tests to complete before exiting. +set +e +# Use RTN to return a non-zero value if the test fails. +RTN=0 +ROOT=$(pwd) +# Find all requirements.txt in the samples directory (may break on whitespace). +for file in samples/**/requirements.txt; do + cd "$ROOT" + # Navigate to the project folder. + file=$(dirname "$file") + cd "$file" + + echo "------------------------------------------------------------" + echo "- testing $file" + echo "------------------------------------------------------------" + + # Use nox to execute the tests for the project. + python3.6 -m nox -s "$RUN_TESTS_SESSION" + EXIT=$? + + # If this is a periodic build, send the test log to the FlakyBot. + # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. + if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then + chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot + $KOKORO_GFILE_DIR/linux_amd64/flakybot + fi + + if [[ $EXIT -ne 0 ]]; then + RTN=1 + echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" + else + echo -e "\n Testing completed.\n" + fi + +done +cd "$ROOT" + +# Workaround for Kokoro permissions issue: delete secrets +rm testing/{test-env.sh,client-secrets.json,service-account.json} + +exit "$RTN" diff --git a/.kokoro/test-samples.sh b/.kokoro/test-samples.sh index c3001ba08..7f72ef5d1 100755 --- a/.kokoro/test-samples.sh +++ b/.kokoro/test-samples.sh @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +# The default test runner for samples. +# +# For periodic builds, we rewinds the repo to the latest release, and +# run test-samples-impl.sh. # `-e` enables the script to automatically fail when a command fails # `-o pipefail` sets the exit code to the rightmost comment to exit with a non-zero @@ -24,87 +28,19 @@ cd github/python-dialogflow # Run periodic samples tests at latest release if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then + # preserving the test runner implementation. + cp .kokoro/test-samples-impl.sh "${TMPDIR}/test-samples-impl.sh" + echo "--- IMPORTANT IMPORTANT IMPORTANT ---" + echo "Now we rewind the repo back to the latest release..." LATEST_RELEASE=$(git describe --abbrev=0 --tags) git checkout $LATEST_RELEASE -fi - -# Exit early if samples directory doesn't exist -if [ ! -d "./samples" ]; then - echo "No tests run. `./samples` not found" - exit 0 -fi - -# Disable buffering, so that the logs stream through. -export PYTHONUNBUFFERED=1 - -# Debug: show build environment -env | grep KOKORO - -# Install nox -python3.6 -m pip install --upgrade --quiet nox - -# Use secrets acessor service account to get secrets -if [[ -f "${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" ]]; then - gcloud auth activate-service-account \ - --key-file="${KOKORO_GFILE_DIR}/secrets_viewer_service_account.json" \ - --project="cloud-devrel-kokoro-resources" -fi - -# This script will create 3 files: -# - testing/test-env.sh -# - testing/service-account.json -# - testing/client-secrets.json -./scripts/decrypt-secrets.sh - -source ./testing/test-env.sh -export GOOGLE_APPLICATION_CREDENTIALS=$(pwd)/testing/service-account.json - -# For cloud-run session, we activate the service account for gcloud sdk. -gcloud auth activate-service-account \ - --key-file "${GOOGLE_APPLICATION_CREDENTIALS}" - -export GOOGLE_CLIENT_SECRETS=$(pwd)/testing/client-secrets.json - -echo -e "\n******************** TESTING PROJECTS ********************" - -# Switch to 'fail at end' to allow all tests to complete before exiting. -set +e -# Use RTN to return a non-zero value if the test fails. -RTN=0 -ROOT=$(pwd) -# Find all requirements.txt in the samples directory (may break on whitespace). -for file in samples/**/requirements.txt; do - cd "$ROOT" - # Navigate to the project folder. - file=$(dirname "$file") - cd "$file" - - echo "------------------------------------------------------------" - echo "- testing $file" - echo "------------------------------------------------------------" - - # Use nox to execute the tests for the project. - python3.6 -m nox -s "$RUN_TESTS_SESSION" - EXIT=$? - - # If this is a periodic build, send the test log to the FlakyBot. - # See https://github.com/googleapis/repo-automation-bots/tree/master/packages/flakybot. - if [[ $KOKORO_BUILD_ARTIFACTS_SUBDIR = *"periodic"* ]]; then - chmod +x $KOKORO_GFILE_DIR/linux_amd64/flakybot - $KOKORO_GFILE_DIR/linux_amd64/flakybot + echo "The current head is: " + echo $(git rev-parse --verify HEAD) + echo "--- IMPORTANT IMPORTANT IMPORTANT ---" + # move back the test runner implementation if there's no file. + if [ ! -f .kokoro/test-samples-impl.sh ]; then + cp "${TMPDIR}/test-samples-impl.sh" .kokoro/test-samples-impl.sh fi +fi - if [[ $EXIT -ne 0 ]]; then - RTN=1 - echo -e "\n Testing failed: Nox returned a non-zero exit code. \n" - else - echo -e "\n Testing completed.\n" - fi - -done -cd "$ROOT" - -# Workaround for Kokoro permissions issue: delete secrets -rm testing/{test-env.sh,client-secrets.json,service-account.json} - -exit "$RTN" +exec .kokoro/test-samples-impl.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a9024b15d..32302e488 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -12,6 +12,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.4 + rev: 3.9.0 hooks: - id: flake8 diff --git a/google/cloud/dialogflow/__init__.py b/google/cloud/dialogflow/__init__.py index d84ba598d..a766e6b13 100644 --- a/google/cloud/dialogflow/__init__.py +++ b/google/cloud/dialogflow/__init__.py @@ -100,8 +100,6 @@ from google.cloud.dialogflow_v2.types.audio_config import SpeechWordInfo from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender from google.cloud.dialogflow_v2.types.audio_config import SynthesizeSpeechConfig -from google.cloud.dialogflow_v2.types.audio_config import TelephonyDtmf -from google.cloud.dialogflow_v2.types.audio_config import TelephonyDtmfEvents from google.cloud.dialogflow_v2.types.audio_config import VoiceSelectionParams from google.cloud.dialogflow_v2.types.context import Context from google.cloud.dialogflow_v2.types.context import CreateContextRequest @@ -111,16 +109,11 @@ from google.cloud.dialogflow_v2.types.context import ListContextsRequest from google.cloud.dialogflow_v2.types.context import ListContextsResponse from google.cloud.dialogflow_v2.types.context import UpdateContextRequest -from google.cloud.dialogflow_v2.types.conversation import CallMatcher from google.cloud.dialogflow_v2.types.conversation import CompleteConversationRequest from google.cloud.dialogflow_v2.types.conversation import Conversation from google.cloud.dialogflow_v2.types.conversation import ConversationPhoneNumber -from google.cloud.dialogflow_v2.types.conversation import CreateCallMatcherRequest from google.cloud.dialogflow_v2.types.conversation import CreateConversationRequest -from google.cloud.dialogflow_v2.types.conversation import DeleteCallMatcherRequest from google.cloud.dialogflow_v2.types.conversation import GetConversationRequest -from google.cloud.dialogflow_v2.types.conversation import ListCallMatchersRequest -from google.cloud.dialogflow_v2.types.conversation import ListCallMatchersResponse from google.cloud.dialogflow_v2.types.conversation import ListConversationsRequest from google.cloud.dialogflow_v2.types.conversation import ListConversationsResponse from google.cloud.dialogflow_v2.types.conversation import ListMessagesRequest @@ -207,21 +200,17 @@ from google.cloud.dialogflow_v2.types.participant import AnalyzeContentResponse from google.cloud.dialogflow_v2.types.participant import AnnotatedMessagePart from google.cloud.dialogflow_v2.types.participant import ArticleAnswer -from google.cloud.dialogflow_v2.types.participant import AudioInput from google.cloud.dialogflow_v2.types.participant import AutomatedAgentReply from google.cloud.dialogflow_v2.types.participant import CreateParticipantRequest from google.cloud.dialogflow_v2.types.participant import DtmfParameters from google.cloud.dialogflow_v2.types.participant import FaqAnswer from google.cloud.dialogflow_v2.types.participant import GetParticipantRequest -from google.cloud.dialogflow_v2.types.participant import InputTextConfig from google.cloud.dialogflow_v2.types.participant import ListParticipantsRequest from google.cloud.dialogflow_v2.types.participant import ListParticipantsResponse from google.cloud.dialogflow_v2.types.participant import Message from google.cloud.dialogflow_v2.types.participant import MessageAnnotation from google.cloud.dialogflow_v2.types.participant import OutputAudio from google.cloud.dialogflow_v2.types.participant import Participant -from google.cloud.dialogflow_v2.types.participant import StreamingAnalyzeContentRequest -from google.cloud.dialogflow_v2.types.participant import StreamingAnalyzeContentResponse from google.cloud.dialogflow_v2.types.participant import SuggestArticlesRequest from google.cloud.dialogflow_v2.types.participant import SuggestArticlesResponse from google.cloud.dialogflow_v2.types.participant import SuggestFaqAnswersRequest @@ -281,7 +270,6 @@ "AnswerRecordsClient", "ArticleAnswer", "AudioEncoding", - "AudioInput", "AutomatedAgentConfig", "AutomatedAgentReply", "BatchCreateEntitiesRequest", @@ -293,7 +281,6 @@ "BatchUpdateEntityTypesResponse", "BatchUpdateIntentsRequest", "BatchUpdateIntentsResponse", - "CallMatcher", "CompleteConversationRequest", "Context", "ContextsAsyncClient", @@ -306,7 +293,6 @@ "ConversationProfilesClient", "ConversationsAsyncClient", "ConversationsClient", - "CreateCallMatcherRequest", "CreateContextRequest", "CreateConversationProfileRequest", "CreateConversationRequest", @@ -318,7 +304,6 @@ "CreateSessionEntityTypeRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", - "DeleteCallMatcherRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", @@ -359,7 +344,6 @@ "HumanAgentHandoffConfig", "ImportAgentRequest", "InputAudioConfig", - "InputTextConfig", "Intent", "IntentBatch", "IntentView", @@ -371,8 +355,6 @@ "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", - "ListCallMatchersRequest", - "ListCallMatchersResponse", "ListContextsRequest", "ListContextsResponse", "ListConversationProfilesRequest", @@ -427,8 +409,6 @@ "SpeechToTextConfig", "SpeechWordInfo", "SsmlVoiceGender", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", @@ -439,8 +419,6 @@ "SuggestionFeature", "SuggestionResult", "SynthesizeSpeechConfig", - "TelephonyDtmf", - "TelephonyDtmfEvents", "TextInput", "TrainAgentRequest", "UpdateAnswerRecordRequest", diff --git a/google/cloud/dialogflow_v2/__init__.py b/google/cloud/dialogflow_v2/__init__.py index 574b1a369..1bc06d15b 100644 --- a/google/cloud/dialogflow_v2/__init__.py +++ b/google/cloud/dialogflow_v2/__init__.py @@ -57,8 +57,6 @@ from .types.audio_config import SpeechWordInfo from .types.audio_config import SsmlVoiceGender from .types.audio_config import SynthesizeSpeechConfig -from .types.audio_config import TelephonyDtmf -from .types.audio_config import TelephonyDtmfEvents from .types.audio_config import VoiceSelectionParams from .types.context import Context from .types.context import CreateContextRequest @@ -68,16 +66,11 @@ from .types.context import ListContextsRequest from .types.context import ListContextsResponse from .types.context import UpdateContextRequest -from .types.conversation import CallMatcher from .types.conversation import CompleteConversationRequest from .types.conversation import Conversation from .types.conversation import ConversationPhoneNumber -from .types.conversation import CreateCallMatcherRequest from .types.conversation import CreateConversationRequest -from .types.conversation import DeleteCallMatcherRequest from .types.conversation import GetConversationRequest -from .types.conversation import ListCallMatchersRequest -from .types.conversation import ListCallMatchersResponse from .types.conversation import ListConversationsRequest from .types.conversation import ListConversationsResponse from .types.conversation import ListMessagesRequest @@ -146,21 +139,17 @@ from .types.participant import AnalyzeContentResponse from .types.participant import AnnotatedMessagePart from .types.participant import ArticleAnswer -from .types.participant import AudioInput from .types.participant import AutomatedAgentReply from .types.participant import CreateParticipantRequest from .types.participant import DtmfParameters from .types.participant import FaqAnswer from .types.participant import GetParticipantRequest -from .types.participant import InputTextConfig from .types.participant import ListParticipantsRequest from .types.participant import ListParticipantsResponse from .types.participant import Message from .types.participant import MessageAnnotation from .types.participant import OutputAudio from .types.participant import Participant -from .types.participant import StreamingAnalyzeContentRequest -from .types.participant import StreamingAnalyzeContentResponse from .types.participant import SuggestArticlesRequest from .types.participant import SuggestArticlesResponse from .types.participant import SuggestFaqAnswersRequest @@ -207,7 +196,6 @@ "AnswerRecordsClient", "ArticleAnswer", "AudioEncoding", - "AudioInput", "AutomatedAgentConfig", "AutomatedAgentReply", "BatchCreateEntitiesRequest", @@ -219,7 +207,6 @@ "BatchUpdateEntityTypesResponse", "BatchUpdateIntentsRequest", "BatchUpdateIntentsResponse", - "CallMatcher", "CompleteConversationRequest", "Context", "ContextsClient", @@ -228,7 +215,7 @@ "ConversationPhoneNumber", "ConversationProfile", "ConversationProfilesClient", - "CreateCallMatcherRequest", + "ConversationsClient", "CreateContextRequest", "CreateConversationProfileRequest", "CreateConversationRequest", @@ -240,7 +227,6 @@ "CreateSessionEntityTypeRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", - "DeleteCallMatcherRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", @@ -278,18 +264,14 @@ "HumanAgentHandoffConfig", "ImportAgentRequest", "InputAudioConfig", - "InputTextConfig", "Intent", "IntentBatch", "IntentView", "IntentsClient", "KnowledgeBase", - "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", - "ListCallMatchersRequest", - "ListCallMatchersResponse", "ListContextsRequest", "ListContextsResponse", "ListConversationProfilesRequest", @@ -341,8 +323,6 @@ "SpeechToTextConfig", "SpeechWordInfo", "SsmlVoiceGender", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", @@ -353,8 +333,6 @@ "SuggestionFeature", "SuggestionResult", "SynthesizeSpeechConfig", - "TelephonyDtmf", - "TelephonyDtmfEvents", "TextInput", "TrainAgentRequest", "UpdateAnswerRecordRequest", @@ -371,5 +349,5 @@ "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "ConversationsClient", + "KnowledgeBasesClient", ) diff --git a/google/cloud/dialogflow_v2/proto/agent.proto b/google/cloud/dialogflow_v2/proto/agent.proto index 4ac05cd2a..72ff1b336 100644 --- a/google/cloud/dialogflow_v2/proto/agent.proto +++ b/google/cloud/dialogflow_v2/proto/agent.proto @@ -44,6 +44,9 @@ service Agents { rpc GetAgent(GetAgentRequest) returns (Agent) { option (google.api.http) = { get: "/v2/{parent=projects/*}/agent" + additional_bindings { + get: "/v2/{parent=projects/*/locations/*}/agent" + } }; option (google.api.method_signature) = "parent"; } @@ -53,6 +56,10 @@ service Agents { option (google.api.http) = { post: "/v2/{agent.parent=projects/*}/agent" body: "agent" + additional_bindings { + post: "/v2/{agent.parent=projects/*/locations/*}/agent" + body: "agent" + } }; option (google.api.method_signature) = "agent"; } @@ -61,6 +68,9 @@ service Agents { rpc DeleteAgent(DeleteAgentRequest) returns (google.protobuf.Empty) { option (google.api.http) = { delete: "/v2/{parent=projects/*}/agent" + additional_bindings { + delete: "/v2/{parent=projects/*/locations/*}/agent" + } }; option (google.api.method_signature) = "parent"; } @@ -75,6 +85,9 @@ service Agents { rpc SearchAgents(SearchAgentsRequest) returns (SearchAgentsResponse) { option (google.api.http) = { get: "/v2/{parent=projects/*}/agent:search" + additional_bindings { + get: "/v2/{parent=projects/*/locations/*}/agent:search" + } }; option (google.api.method_signature) = "parent"; } @@ -86,6 +99,10 @@ service Agents { option (google.api.http) = { post: "/v2/{parent=projects/*}/agent:train" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*}/agent:train" + body: "*" + } }; option (google.api.method_signature) = "parent"; option (google.longrunning.operation_info) = { @@ -101,6 +118,10 @@ service Agents { option (google.api.http) = { post: "/v2/{parent=projects/*}/agent:export" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*}/agent:export" + body: "*" + } }; option (google.api.method_signature) = "parent"; option (google.longrunning.operation_info) = { @@ -126,6 +147,10 @@ service Agents { option (google.api.http) = { post: "/v2/{parent=projects/*}/agent:import" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*}/agent:import" + body: "*" + } }; option (google.longrunning.operation_info) = { response_type: "google.protobuf.Empty" @@ -149,6 +174,10 @@ service Agents { option (google.api.http) = { post: "/v2/{parent=projects/*}/agent:restore" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*}/agent:restore" + body: "*" + } }; option (google.longrunning.operation_info) = { response_type: "google.protobuf.Empty" @@ -161,6 +190,9 @@ service Agents { rpc GetValidationResult(GetValidationResultRequest) returns (ValidationResult) { option (google.api.http) = { get: "/v2/{parent=projects/*}/agent/validationResult" + additional_bindings { + get: "/v2/{parent=projects/*/locations/*}/agent/validationResult" + } }; } } diff --git a/google/cloud/dialogflow_v2/proto/answer_record.proto b/google/cloud/dialogflow_v2/proto/answer_record.proto index 1afb47e63..3fb729107 100644 --- a/google/cloud/dialogflow_v2/proto/answer_record.proto +++ b/google/cloud/dialogflow_v2/proto/answer_record.proto @@ -33,7 +33,8 @@ option java_outer_classname = "AnswerRecordsProto"; option java_package = "com.google.cloud.dialogflow.v2"; option objc_class_prefix = "DF"; -// Service for managing [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. +// Service for managing +// [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord]. service AnswerRecords { option (google.api.default_host) = "dialogflow.googleapis.com"; option (google.api.oauth_scopes) = @@ -42,7 +43,8 @@ service AnswerRecords { // Returns the list of all answer records in the specified project in reverse // chronological order. - rpc ListAnswerRecords(ListAnswerRecordsRequest) returns (ListAnswerRecordsResponse) { + rpc ListAnswerRecords(ListAnswerRecordsRequest) + returns (ListAnswerRecordsResponse) { option (google.api.http) = { get: "/v2/{parent=projects/*}/answerRecords" additional_bindings { @@ -87,9 +89,11 @@ service AnswerRecords { // A typical workflow for customers provide feedback to an answer is: // // 1. For human agent assistant, customers get suggestion via ListSuggestions -// API. Together with the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the -// customers. -// 2. The customer uses the [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] to call the +// API. Together with the answers, +// [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are +// returned to the customers. +// 2. The customer uses the +// [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] to call the // [UpdateAnswerRecord][] method to send feedback about a specific answer // that they believe is wrong. message AnswerRecord { @@ -105,18 +109,20 @@ message AnswerRecord { string name = 1; // Required. The AnswerFeedback for this record. You can set this with - // [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord] in order to give us feedback about - // this answer. + // [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2.AnswerRecords.UpdateAnswerRecord] + // in order to give us feedback about this answer. AnswerFeedback answer_feedback = 2 [(google.api.field_behavior) = REQUIRED]; // The record for this answer. oneof record { // Output only. The record for human agent assistant. - AgentAssistantRecord agent_assistant_record = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + AgentAssistantRecord agent_assistant_record = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; } } -// Request message for [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. +// Request message for +// [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. message ListAnswerRecordsRequest { // Required. The project to list all answer records for in reverse // chronological order. Format: `projects//locations/ -// ;purpose=Goog-ContactCenter-Conversation`. -// * Or, if that doesn't work, matching incoming [SIP -// headers](https://tools.ietf.org/html/rfc3261#section-7.3) -// against any [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] for the conversation. -// -// If an incoming SIP call without valid `Call-Info` header matches to zero or -// multiple conversations with `CallMatcher`, we reject it. -// -// A call matcher contains equality conditions for SIP headers that all have -// to be fulfilled in order for a SIP call to match. -// -// The matched SIP headers consist of well-known headers (`To`, `From`, -// `Call-ID`) and custom headers. A [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] is only valid if it -// specifies: -// -// * At least 1 custom header, -// * or at least 2 well-known headers. -message CallMatcher { - option (google.api.resource) = { - type: "dialogflow.googleapis.com/CallMatcher" - pattern: "projects/{project}/conversations/{conversation}/callMatchers/{call_matcher}" - pattern: "projects/{project}/locations/{location}/conversations/{conversation}/callMatchers/{call_matcher}" - }; - - // Custom SIP headers. See the [description of headers in - // the RFC](https://tools.ietf.org/html/rfc3261#section-7.3). - message CustomHeaders { - // Cisco's proprietary `Cisco-Guid` header. - string cisco_guid = 1; - } - - // Output only. The unique identifier of this call matcher. - // Format: `projects//locations//conversations//callMatchers/`. - string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // Value of the [`To` - // header](https://tools.ietf.org/html/rfc3261#section-8.1.1.2) to match. If - // empty or unspecified, we don't match to the - // [`To` header](https://tools.ietf.org/html/rfc3261#section-8.1.1.2). - string to_header = 2; - - // Value of the [`From` - // header](https://tools.ietf.org/html/rfc3261#section-8.1.1.3) to match. If - // empty or unspecified, we don't match to the - // [`From` header](https://tools.ietf.org/html/rfc3261#section-8.1.1.3). - string from_header = 3; - - // Value of the [`Call-ID` - // header](https://tools.ietf.org/html/rfc3261#section-8.1.1.4) to match. If - // empty or unspecified, we don't match to the - // [`Call-ID` header](https://tools.ietf.org/html/rfc3261#section-8.1.1.4). - string call_id_header = 4; - - // Custom SIP headers that must match. - CustomHeaders custom_headers = 5; -} - // The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. message CreateConversationRequest { // Required. Resource identifier of the project creating the conversation. @@ -410,66 +308,6 @@ message CompleteConversationRequest { ]; } -// The request message for [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2.Conversations.CreateCallMatcher]. -message CreateCallMatcherRequest { - // Required. Resource identifier of the conversation adding the call matcher. - // Format: `projects//locations//conversations/`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "dialogflow.googleapis.com/CallMatcher" - } - ]; - - // Required. The call matcher to create. - CallMatcher call_matcher = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// The request message for [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. -message ListCallMatchersRequest { - // Required. The conversation to list all call matchers from. - // Format: `projects//locations//conversations/`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "dialogflow.googleapis.com/CallMatcher" - } - ]; - - // Optional. The maximum number of items to return in a single page. By - // default 100 and at most 1000. - int32 page_size = 2 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The next_page_token value returned from a previous list request. - string page_token = 3 [(google.api.field_behavior) = OPTIONAL]; -} - -// The response message for [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. -message ListCallMatchersResponse { - // The list of call matchers. There is a maximum number of items - // returned based on the page_size field in the request. - repeated CallMatcher call_matchers = 1; - - // Token to retrieve the next page of results or empty if there are no - // more results in the list. - string next_page_token = 2; -} - -// The request message for [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2.Conversations.DeleteCallMatcher]. -message DeleteCallMatcherRequest { - // Required. The unique identifier of the [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] to delete. - // Format: `projects//locations//conversations//callMatchers/`. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/CallMatcher" - } - ]; -} - // The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. message ListMessagesRequest { // Required. The name of the conversation to list messages for. diff --git a/google/cloud/dialogflow_v2/proto/conversation_profile.proto b/google/cloud/dialogflow_v2/proto/conversation_profile.proto index ea0fc6f02..8194ae224 100644 --- a/google/cloud/dialogflow_v2/proto/conversation_profile.proto +++ b/google/cloud/dialogflow_v2/proto/conversation_profile.proto @@ -434,10 +434,7 @@ message HumanAgentAssistantConfig { // Required. Conversation model resource name. Format: `projects//conversationModels/`. string model = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/ConversationModel" - } + (google.api.field_behavior) = REQUIRED ]; } diff --git a/google/cloud/dialogflow_v2/proto/document.proto b/google/cloud/dialogflow_v2/proto/document.proto index 5ff579960..a3bc4b77b 100644 --- a/google/cloud/dialogflow_v2/proto/document.proto +++ b/google/cloud/dialogflow_v2/proto/document.proto @@ -47,6 +47,9 @@ service Documents { additional_bindings { get: "/v2/{parent=projects/*/locations/*/knowledgeBases/*}/documents" } + additional_bindings { + get: "/v2/{parent=projects/*/agent/knowledgeBases/*}/documents" + } }; option (google.api.method_signature) = "parent"; } @@ -58,6 +61,9 @@ service Documents { additional_bindings { get: "/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}" } + additional_bindings { + get: "/v2/{name=projects/*/agent/knowledgeBases/*/documents/*}" + } }; option (google.api.method_signature) = "name"; } @@ -74,6 +80,10 @@ service Documents { post: "/v2/{parent=projects/*/locations/*/knowledgeBases/*}/documents" body: "document" } + additional_bindings { + post: "/v2/{parent=projects/*/agent/knowledgeBases/*}/documents" + body: "document" + } }; option (google.api.method_signature) = "parent,document"; option (google.longrunning.operation_info) = { @@ -92,6 +102,9 @@ service Documents { additional_bindings { delete: "/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}" } + additional_bindings { + delete: "/v2/{name=projects/*/agent/knowledgeBases/*/documents/*}" + } }; option (google.api.method_signature) = "name"; option (google.longrunning.operation_info) = { @@ -112,6 +125,10 @@ service Documents { patch: "/v2/{document.name=projects/*/locations/*/knowledgeBases/*/documents/*}" body: "document" } + additional_bindings { + patch: "/v2/{document.name=projects/*/agent/knowledgeBases/*/documents/*}" + body: "document" + } }; option (google.api.method_signature) = "document,update_mask"; option (google.longrunning.operation_info) = { @@ -138,6 +155,10 @@ service Documents { post: "/v2/{name=projects/*/locations/*/knowledgeBases/*/documents/*}:reload" body: "*" } + additional_bindings { + post: "/v2/{name=projects/*/agent/knowledgeBases/*/documents/*}:reload" + body: "*" + } }; option (google.api.method_signature) = "name,content_uri"; option (google.longrunning.operation_info) = { diff --git a/google/cloud/dialogflow_v2/proto/entity_type.proto b/google/cloud/dialogflow_v2/proto/entity_type.proto index f8a69ec58..c15b5a188 100644 --- a/google/cloud/dialogflow_v2/proto/entity_type.proto +++ b/google/cloud/dialogflow_v2/proto/entity_type.proto @@ -43,6 +43,9 @@ service EntityTypes { rpc ListEntityTypes(ListEntityTypesRequest) returns (ListEntityTypesResponse) { option (google.api.http) = { get: "/v2/{parent=projects/*/agent}/entityTypes" + additional_bindings { + get: "/v2/{parent=projects/*/locations/*/agent}/entityTypes" + } }; option (google.api.method_signature) = "parent"; option (google.api.method_signature) = "parent,language_code"; @@ -52,6 +55,9 @@ service EntityTypes { rpc GetEntityType(GetEntityTypeRequest) returns (EntityType) { option (google.api.http) = { get: "/v2/{name=projects/*/agent/entityTypes/*}" + additional_bindings { + get: "/v2/{name=projects/*/locations/*/agent/entityTypes/*}" + } }; option (google.api.method_signature) = "name"; option (google.api.method_signature) = "name,language_code"; @@ -62,6 +68,10 @@ service EntityTypes { option (google.api.http) = { post: "/v2/{parent=projects/*/agent}/entityTypes" body: "entity_type" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent}/entityTypes" + body: "entity_type" + } }; option (google.api.method_signature) = "parent,entity_type"; option (google.api.method_signature) = "parent,entity_type,language_code"; @@ -72,6 +82,10 @@ service EntityTypes { option (google.api.http) = { patch: "/v2/{entity_type.name=projects/*/agent/entityTypes/*}" body: "entity_type" + additional_bindings { + patch: "/v2/{entity_type.name=projects/*/locations/*/agent/entityTypes/*}" + body: "entity_type" + } }; option (google.api.method_signature) = "entity_type"; option (google.api.method_signature) = "entity_type,language_code"; @@ -81,6 +95,9 @@ service EntityTypes { rpc DeleteEntityType(DeleteEntityTypeRequest) returns (google.protobuf.Empty) { option (google.api.http) = { delete: "/v2/{name=projects/*/agent/entityTypes/*}" + additional_bindings { + delete: "/v2/{name=projects/*/locations/*/agent/entityTypes/*}" + } }; option (google.api.method_signature) = "name"; } @@ -92,6 +109,10 @@ service EntityTypes { option (google.api.http) = { post: "/v2/{parent=projects/*/agent}/entityTypes:batchUpdate" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent}/entityTypes:batchUpdate" + body: "*" + } }; option (google.longrunning.operation_info) = { response_type: "google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse" @@ -106,6 +127,10 @@ service EntityTypes { option (google.api.http) = { post: "/v2/{parent=projects/*/agent}/entityTypes:batchDelete" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent}/entityTypes:batchDelete" + body: "*" + } }; option (google.api.method_signature) = "parent,entity_type_names"; option (google.longrunning.operation_info) = { @@ -121,6 +146,10 @@ service EntityTypes { option (google.api.http) = { post: "/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchCreate" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchCreate" + body: "*" + } }; option (google.api.method_signature) = "parent,entities"; option (google.api.method_signature) = "parent,entities,language_code"; @@ -140,6 +169,10 @@ service EntityTypes { option (google.api.http) = { post: "/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchUpdate" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchUpdate" + body: "*" + } }; option (google.api.method_signature) = "parent,entities"; option (google.api.method_signature) = "parent,entities,language_code"; @@ -157,6 +190,10 @@ service EntityTypes { option (google.api.http) = { post: "/v2/{parent=projects/*/agent/entityTypes/*}/entities:batchDelete" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent/entityTypes/*}/entities:batchDelete" + body: "*" + } }; option (google.api.method_signature) = "parent,entity_values"; option (google.api.method_signature) = "parent,entity_values,language_code"; diff --git a/google/cloud/dialogflow_v2/proto/environment.proto b/google/cloud/dialogflow_v2/proto/environment.proto index ef094c71e..db8885425 100644 --- a/google/cloud/dialogflow_v2/proto/environment.proto +++ b/google/cloud/dialogflow_v2/proto/environment.proto @@ -43,6 +43,9 @@ service Environments { rpc ListEnvironments(ListEnvironmentsRequest) returns (ListEnvironmentsResponse) { option (google.api.http) = { get: "/v2/{parent=projects/*/agent}/environments" + additional_bindings { + get: "/v2/{parent=projects/*/locations/*/agent}/environments" + } }; } } diff --git a/google/cloud/dialogflow_v2/proto/intent.proto b/google/cloud/dialogflow_v2/proto/intent.proto index e1507a5c9..b61109585 100644 --- a/google/cloud/dialogflow_v2/proto/intent.proto +++ b/google/cloud/dialogflow_v2/proto/intent.proto @@ -47,6 +47,9 @@ service Intents { rpc ListIntents(ListIntentsRequest) returns (ListIntentsResponse) { option (google.api.http) = { get: "/v2/{parent=projects/*/agent}/intents" + additional_bindings { + get: "/v2/{parent=projects/*/locations/*/agent}/intents" + } additional_bindings { get: "/v2/{parent=projects/*/agent/environments/*}/intents" } @@ -59,6 +62,9 @@ service Intents { rpc GetIntent(GetIntentRequest) returns (Intent) { option (google.api.http) = { get: "/v2/{name=projects/*/agent/intents/*}" + additional_bindings { + get: "/v2/{name=projects/*/locations/*/agent/intents/*}" + } }; option (google.api.method_signature) = "name"; option (google.api.method_signature) = "name,language_code"; @@ -69,6 +75,10 @@ service Intents { option (google.api.http) = { post: "/v2/{parent=projects/*/agent}/intents" body: "intent" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent}/intents" + body: "intent" + } }; option (google.api.method_signature) = "parent,intent"; option (google.api.method_signature) = "parent,intent,language_code"; @@ -79,6 +89,10 @@ service Intents { option (google.api.http) = { patch: "/v2/{intent.name=projects/*/agent/intents/*}" body: "intent" + additional_bindings { + patch: "/v2/{intent.name=projects/*/locations/*/agent/intents/*}" + body: "intent" + } }; option (google.api.method_signature) = "intent,language_code"; option (google.api.method_signature) = "intent,language_code,update_mask"; @@ -88,6 +102,9 @@ service Intents { rpc DeleteIntent(DeleteIntentRequest) returns (google.protobuf.Empty) { option (google.api.http) = { delete: "/v2/{name=projects/*/agent/intents/*}" + additional_bindings { + delete: "/v2/{name=projects/*/locations/*/agent/intents/*}" + } }; option (google.api.method_signature) = "name"; } @@ -99,6 +116,10 @@ service Intents { option (google.api.http) = { post: "/v2/{parent=projects/*/agent}/intents:batchUpdate" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent}/intents:batchUpdate" + body: "*" + } }; option (google.api.method_signature) = "parent,intent_batch_uri"; option (google.api.method_signature) = "parent,intent_batch_inline"; @@ -115,6 +136,10 @@ service Intents { option (google.api.http) = { post: "/v2/{parent=projects/*/agent}/intents:batchDelete" body: "*" + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent}/intents:batchDelete" + body: "*" + } }; option (google.api.method_signature) = "parent,intents"; option (google.longrunning.operation_info) = { diff --git a/google/cloud/dialogflow_v2/proto/knowledge_base.proto b/google/cloud/dialogflow_v2/proto/knowledge_base.proto index 52dbed10c..0b1aa8b3e 100644 --- a/google/cloud/dialogflow_v2/proto/knowledge_base.proto +++ b/google/cloud/dialogflow_v2/proto/knowledge_base.proto @@ -45,6 +45,9 @@ service KnowledgeBases { additional_bindings { get: "/v2/{parent=projects/*/locations/*}/knowledgeBases" } + additional_bindings { + get: "/v2/{parent=projects/*/agent}/knowledgeBases" + } }; option (google.api.method_signature) = "parent"; } @@ -56,6 +59,9 @@ service KnowledgeBases { additional_bindings { get: "/v2/{name=projects/*/locations/*/knowledgeBases/*}" } + additional_bindings { + get: "/v2/{name=projects/*/agent/knowledgeBases/*}" + } }; option (google.api.method_signature) = "name"; } @@ -69,6 +75,10 @@ service KnowledgeBases { post: "/v2/{parent=projects/*/locations/*}/knowledgeBases" body: "knowledge_base" } + additional_bindings { + post: "/v2/{parent=projects/*/agent}/knowledgeBases" + body: "knowledge_base" + } }; option (google.api.method_signature) = "parent,knowledge_base"; } @@ -80,6 +90,9 @@ service KnowledgeBases { additional_bindings { delete: "/v2/{name=projects/*/locations/*/knowledgeBases/*}" } + additional_bindings { + delete: "/v2/{name=projects/*/agent/knowledgeBases/*}" + } }; option (google.api.method_signature) = "name"; } @@ -93,6 +106,10 @@ service KnowledgeBases { patch: "/v2/{knowledge_base.name=projects/*/locations/*/knowledgeBases/*}" body: "knowledge_base" } + additional_bindings { + patch: "/v2/{knowledge_base.name=projects/*/agent/knowledgeBases/*}" + body: "knowledge_base" + } }; option (google.api.method_signature) = "knowledge_base,update_mask"; } diff --git a/google/cloud/dialogflow_v2/proto/participant.proto b/google/cloud/dialogflow_v2/proto/participant.proto index 2c6e85736..91aa04543 100644 --- a/google/cloud/dialogflow_v2/proto/participant.proto +++ b/google/cloud/dialogflow_v2/proto/participant.proto @@ -96,7 +96,7 @@ service Participants { // // Note: Always use agent versions for production traffic // sent to virtual agents. See [Versions and - // environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + // environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). rpc AnalyzeContent(AnalyzeContentRequest) returns (AnalyzeContentResponse) { option (google.api.http) = { post: "/v2/{participant=projects/*/conversations/*/participants/*}:analyzeContent" @@ -107,28 +107,9 @@ service Participants { } }; option (google.api.method_signature) = "participant,text_input"; - option (google.api.method_signature) = "participant,audio_input"; option (google.api.method_signature) = "participant,event_input"; } - // Adds a text (chat, for example), or audio (phone recording, for example) - // message from a participant into the conversation. - // Note: This method is only available through the gRPC API (not REST). - // - // The top-level message sent to the client by the server is - // `StreamingAnalyzeContentResponse`. Multiple response messages can be - // returned in order. The first one or more messages contain the - // `recognition_result` field. Each result represents a more complete - // transcript of what the user said. The next message contains the - // `reply_text` field and potentially the `reply_audio` field. The message can - // also contain the `automated_agent_reply` field. - // - // Note: Always use agent versions for production traffic - // sent to virtual agents. See [Versions and - // environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - rpc StreamingAnalyzeContent(stream StreamingAnalyzeContentRequest) returns (stream StreamingAnalyzeContentResponse) { - } - // Gets suggested articles for a participant based on specific historical // messages. rpc SuggestArticles(SuggestArticlesRequest) returns (SuggestArticlesResponse) { @@ -317,9 +298,6 @@ message AnalyzeContentRequest { // The natural language text to be processed. TextInput text_input = 6; - // The natural language speech audio to be processed. - AudioInput audio_input = 7; - // An input event to send to Dialogflow. EventInput event_input = 8; } @@ -389,143 +367,6 @@ message AnalyzeContentResponse { DtmfParameters dtmf_parameters = 9; } -// The top-level message sent by the client to the -// [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] method. -// -// Multiple request messages should be sent in order: -// -// 1. The first message must contain -// [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], -// [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] and optionally -// [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. If you want -// to receive an audio response, it should also contain -// [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. -// The message must not contain -// [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. -// -// 2. If [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] in the first message -// was set to [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], -// all subsequent messages must contain -// [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] to continue -// with Speech recognition. -// However, note that: -// -// * Dialogflow will bill you for the audio so far. -// * Dialogflow discards all Speech recognition results in favor of the -// text input. -// -// 3. If [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] in the first message was set -// to [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], then the second message -// must contain only [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. -// Moreover, you must not send more than two messages. -// -// After you sent all input, you must half-close or abort the request stream. -message StreamingAnalyzeContentRequest { - // Required. The name of the participant this text comes from. - // Format: `projects//locations//conversations//participants/`. - string participant = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/Participant" - } - ]; - - // Required. The input config. - oneof config { - // Instructs the speech recognizer how to process the speech audio. - InputAudioConfig audio_config = 2; - - // The natural language text to be processed. - InputTextConfig text_config = 3; - } - - // Speech synthesis configuration. - // The speech synthesis settings for a virtual agent that may be configured - // for the associated conversation profile are not used when calling - // StreamingAnalyzeContent. If this configuration is not supplied, speech - // synthesis is disabled. - OutputAudioConfig reply_audio_config = 4; - - // Required. The input. - oneof input { - // The input audio content to be recognized. Must be sent if `audio_config` - // is set in the first message. The complete audio over all streaming - // messages must not exceed 1 minute. - bytes input_audio = 5; - - // The UTF-8 encoded natural language text to be processed. Must be sent if - // `text_config` is set in the first message. Text length must not exceed - // 256 bytes. The `input_text` field can be only sent once. - string input_text = 6; - - // The DTMF digits used to invoke intent and fill in parameter value. - // - // This input is ignored if the previous response indicated that DTMF input - // is not accepted. - TelephonyDtmfEvents input_dtmf = 9; - } - - // Parameters for a Dialogflow virtual-agent query. - QueryParameters query_params = 7; -} - -// The top-level message returned from the `StreamingAnalyzeContent` method. -// -// Multiple response messages can be returned in order: -// -// 1. If the input was set to streaming audio, the first one or more messages -// contain `recognition_result`. Each `recognition_result` represents a more -// complete transcript of what the user said. The last `recognition_result` -// has `is_final` set to `true`. -// -// 2. The next message contains `reply_text` and optionally `reply_audio` -// returned by an agent. This message may also contain -// `automated_agent_reply`. -message StreamingAnalyzeContentResponse { - // The result of speech recognition. - StreamingRecognitionResult recognition_result = 1; - - // The output text content. - // This field is set if an automated agent responded with a text for the user. - string reply_text = 2; - - // The audio data bytes encoded as specified in the request. - // This field is set if: - // - // - The `reply_audio_config` field is specified in the request. - // - The automated agent, which this output comes from, responded with audio. - // In such case, the `reply_audio.config` field contains settings used to - // synthesize the speech. - // - // In some scenarios, multiple output audio fields may be present in the - // response structure. In these cases, only the top-most-level audio output - // has content. - OutputAudio reply_audio = 3; - - // Only set if a Dialogflow automated agent has responded. - // Note that: [AutomatedAgentReply.detect_intent_response.output_audio][] - // and [AutomatedAgentReply.detect_intent_response.output_audio_config][] - // are always empty, use [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] instead. - AutomatedAgentReply automated_agent_reply = 4; - - // Message analyzed by CCAI. - Message message = 6; - - // The suggestions for most recent human agent. The order is the same as - // [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of - // [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config]. - repeated SuggestionResult human_agent_suggestion_results = 7; - - // The suggestions for end user. The order is the same as - // [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of - // [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config]. - repeated SuggestionResult end_user_suggestion_results = 8; - - // Indicates the parameters of DTMF. - DtmfParameters dtmf_parameters = 10; -} - // The request message for [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. message SuggestArticlesRequest { // Required. The name of the participant to fetch suggestion for. @@ -620,17 +461,6 @@ message SuggestFaqAnswersResponse { int32 context_size = 3; } -// Represents the natural language speech audio to be processed. -message AudioInput { - // Required. Instructs the speech recognizer how to process the speech audio. - InputAudioConfig config = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. The natural language speech audio to be processed. - // A single request can contain up to 1 minute of speech audio data. - // The transcribed text cannot contain more than 256 bytes. - bytes audio = 2 [(google.api.field_behavior) = REQUIRED]; -} - // Represents the natural language speech audio to be played to the end user. message OutputAudio { // Instructs the speech synthesizer how to generate the speech @@ -720,14 +550,6 @@ message SuggestionResult { } } -// Defines the language used in the input text. -message InputTextConfig { - // Required. The language of this conversational query. See [Language - // Support](https://cloud.google.com/dialogflow/docs/reference/language) - // for a list of the currently supported language codes. - string language_code = 1 [(google.api.field_behavior) = REQUIRED]; -} - // Represents a part of a message possibly annotated with an entity. The part // can be an entity or purely a part of the message between two entities or // message start/end. diff --git a/google/cloud/dialogflow_v2/proto/session.proto b/google/cloud/dialogflow_v2/proto/session.proto index 338489652..13e3abff7 100644 --- a/google/cloud/dialogflow_v2/proto/session.proto +++ b/google/cloud/dialogflow_v2/proto/session.proto @@ -69,6 +69,14 @@ service Sessions { post: "/v2/{session=projects/*/agent/environments/*/users/*/sessions/*}:detectIntent" body: "*" } + additional_bindings { + post: "/v2/{session=projects/*/locations/*/agent/sessions/*}:detectIntent" + body: "*" + } + additional_bindings { + post: "/v2/{session=projects/*/locations/*/agent/environments/*/users/*/sessions/*}:detectIntent" + body: "*" + } }; option (google.api.method_signature) = "session,query_input"; } diff --git a/google/cloud/dialogflow_v2/proto/session_entity_type.proto b/google/cloud/dialogflow_v2/proto/session_entity_type.proto index 0eceed81c..cac38be77 100644 --- a/google/cloud/dialogflow_v2/proto/session_entity_type.proto +++ b/google/cloud/dialogflow_v2/proto/session_entity_type.proto @@ -50,6 +50,12 @@ service SessionEntityTypes { additional_bindings { get: "/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/entityTypes" } + additional_bindings { + get: "/v2/{parent=projects/*/locations/*/agent/sessions/*}/entityTypes" + } + additional_bindings { + get: "/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/entityTypes" + } }; option (google.api.method_signature) = "parent"; } @@ -65,6 +71,12 @@ service SessionEntityTypes { additional_bindings { get: "/v2/{name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}" } + additional_bindings { + get: "/v2/{name=projects/*/locations/*/agent/sessions/*/entityTypes/*}" + } + additional_bindings { + get: "/v2/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}" + } }; option (google.api.method_signature) = "name"; } @@ -85,6 +97,14 @@ service SessionEntityTypes { post: "/v2/{parent=projects/*/agent/environments/*/users/*/sessions/*}/entityTypes" body: "session_entity_type" } + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent/sessions/*}/entityTypes" + body: "session_entity_type" + } + additional_bindings { + post: "/v2/{parent=projects/*/locations/*/agent/environments/*/users/*/sessions/*}/entityTypes" + body: "session_entity_type" + } }; option (google.api.method_signature) = "parent,session_entity_type"; } @@ -102,6 +122,14 @@ service SessionEntityTypes { patch: "/v2/{session_entity_type.name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}" body: "session_entity_type" } + additional_bindings { + patch: "/v2/{session_entity_type.name=projects/*/locations/*/agent/sessions/*/entityTypes/*}" + body: "session_entity_type" + } + additional_bindings { + patch: "/v2/{session_entity_type.name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}" + body: "session_entity_type" + } }; option (google.api.method_signature) = "session_entity_type"; option (google.api.method_signature) = "session_entity_type,update_mask"; @@ -118,6 +146,12 @@ service SessionEntityTypes { additional_bindings { delete: "/v2/{name=projects/*/agent/environments/*/users/*/sessions/*/entityTypes/*}" } + additional_bindings { + delete: "/v2/{name=projects/*/locations/*/agent/sessions/*/entityTypes/*}" + } + additional_bindings { + delete: "/v2/{name=projects/*/locations/*/agent/environments/*/users/*/sessions/*/entityTypes/*}" + } }; option (google.api.method_signature) = "name"; } diff --git a/google/cloud/dialogflow_v2/services/agents/transports/base.py b/google/cloud/dialogflow_v2/services/agents/transports/base.py index 8987cfbe7..b41e474a7 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/base.py @@ -77,10 +77,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -88,6 +88,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -97,20 +100,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/agents/transports/grpc.py b/google/cloud/dialogflow_v2/services/agents/transports/grpc.py index ff1f4bb3f..3ace9db2e 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/grpc.py @@ -111,7 +111,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,18 +173,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -215,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py index 1bb87d75c..22f02de20 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +218,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/answer_records/async_client.py b/google/cloud/dialogflow_v2/services/answer_records/async_client.py index aad1111e5..cd5148715 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/async_client.py +++ b/google/cloud/dialogflow_v2/services/answer_records/async_client.py @@ -209,7 +209,7 @@ async def list_answer_records( Returns: google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsAsyncPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -324,11 +324,12 @@ async def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the customers. + 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe - is wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe is + wrong. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/dialogflow_v2/services/answer_records/client.py b/google/cloud/dialogflow_v2/services/answer_records/client.py index 3a04afa04..9940b63f1 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/client.py +++ b/google/cloud/dialogflow_v2/services/answer_records/client.py @@ -378,7 +378,7 @@ def list_answer_records( Returns: google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -494,11 +494,12 @@ def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the customers. + 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe - is wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe is + wrong. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/base.py b/google/cloud/dialogflow_v2/services/answer_records/transports/base.py index 01e16c3e5..d82b61291 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/base.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py index f8c4c1a0c..38373a7c5 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py @@ -108,7 +108,9 @@ def __init__( 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) @@ -116,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -187,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -211,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py index e71fd9450..eec5d7448 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py @@ -63,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -141,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -153,7 +153,9 @@ def __init__( 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) @@ -161,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -232,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/base.py b/google/cloud/dialogflow_v2/services/contexts/transports/base.py index 607281545..350f2d7fc 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/base.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/base.py @@ -74,10 +74,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,6 +85,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -94,20 +97,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py b/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py index dfeab86c6..7e3153ef0 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py @@ -108,7 +108,9 @@ def __init__( 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) @@ -116,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -187,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -211,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py index 680211350..3e5d003b5 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py @@ -63,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -141,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -153,7 +153,9 @@ def __init__( 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) @@ -161,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -232,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py index fad34b214..5768948c2 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py index 41f695f7e..9af6dd273 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py @@ -111,7 +111,9 @@ def __init__( 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) @@ -119,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,17 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py index acb03edac..d6ec1c60c 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/conversations/async_client.py b/google/cloud/dialogflow_v2/services/conversations/async_client.py index 5e1ee33d9..7afd626e5 100644 --- a/google/cloud/dialogflow_v2/services/conversations/async_client.py +++ b/google/cloud/dialogflow_v2/services/conversations/async_client.py @@ -49,8 +49,6 @@ class ConversationsAsyncClient: DEFAULT_ENDPOINT = ConversationsClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = ConversationsClient.DEFAULT_MTLS_ENDPOINT - call_matcher_path = staticmethod(ConversationsClient.call_matcher_path) - parse_call_matcher_path = staticmethod(ConversationsClient.parse_call_matcher_path) conversation_path = staticmethod(ConversationsClient.conversation_path) parse_conversation_path = staticmethod(ConversationsClient.parse_conversation_path) conversation_profile_path = staticmethod( @@ -534,272 +532,6 @@ async def complete_conversation( # Done; return the response. return response - async def create_call_matcher( - self, - request: conversation.CreateCallMatcherRequest = None, - *, - parent: str = None, - call_matcher: conversation.CallMatcher = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.CallMatcher: - r"""Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.CreateCallMatcherRequest`): - The request object. The request message for - [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2.Conversations.CreateCallMatcher]. - parent (:class:`str`): - Required. Resource identifier of the conversation adding - the call matcher. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - call_matcher (:class:`google.cloud.dialogflow_v2.types.CallMatcher`): - Required. The call matcher to create. - This corresponds to the ``call_matcher`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.CallMatcher: - Represents a call matcher that describes criteria for matching incoming SIP - calls to a conversation. When Dialogflow get a SIP - call from a third-party carrier, Dialogflow matches - the call to an existing conversation by either: - - - Extracting the conversation id from the [Call-Info - header](\ https://tools.ietf.org/html/rfc3261#section-20.9), - e.g. Call-Info: - - ;purpose=Goog-ContactCenter-Conversation. - - \* Or, if that doesn't work, matching incoming [SIP - headers](\ https://tools.ietf.org/html/rfc3261#section-7.3) - against any - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] - for the conversation. - - If an incoming SIP call without valid Call-Info - header matches to zero or multiple conversations with - CallMatcher, we reject it. - - A call matcher contains equality conditions for SIP - headers that all have to be fulfilled in order for a - SIP call to match. - - The matched SIP headers consist of well-known headers - (To, From, Call-ID) and custom headers. A - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] - is only valid if it specifies: - - - At least 1 custom header, - - or at least 2 well-known headers. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, call_matcher]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = conversation.CreateCallMatcherRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if call_matcher is not None: - request.call_matcher = call_matcher - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_call_matcher, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_call_matchers( - self, - request: conversation.ListCallMatchersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCallMatchersAsyncPager: - r"""Returns the list of all call matchers in the - specified conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.ListCallMatchersRequest`): - The request object. The request message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. - parent (:class:`str`): - Required. The conversation to list all call matchers - from. Format: - ``projects//locations//conversations/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversations.pagers.ListCallMatchersAsyncPager: - The response message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = conversation.ListCallMatchersRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_call_matchers, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # 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.ListCallMatchersAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_call_matcher( - self, - request: conversation.DeleteCallMatcherRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Requests deletion of a call matcher. - - Args: - request (:class:`google.cloud.dialogflow_v2.types.DeleteCallMatcherRequest`): - The request object. The request message for - [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2.Conversations.DeleteCallMatcher]. - name (:class:`str`): - Required. The unique identifier of the - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] to - delete. Format: - ``projects//locations//conversations//callMatchers/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = conversation.DeleteCallMatcherRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_call_matcher, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - await rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - async def list_messages( self, request: conversation.ListMessagesRequest = None, diff --git a/google/cloud/dialogflow_v2/services/conversations/client.py b/google/cloud/dialogflow_v2/services/conversations/client.py index b03655065..16e68f100 100644 --- a/google/cloud/dialogflow_v2/services/conversations/client.py +++ b/google/cloud/dialogflow_v2/services/conversations/client.py @@ -158,22 +158,6 @@ def transport(self) -> ConversationsTransport: """ return self._transport - @staticmethod - def call_matcher_path(project: str, conversation: str, call_matcher: str,) -> str: - """Return a fully-qualified call_matcher string.""" - return "projects/{project}/conversations/{conversation}/callMatchers/{call_matcher}".format( - project=project, conversation=conversation, call_matcher=call_matcher, - ) - - @staticmethod - def parse_call_matcher_path(path: str) -> Dict[str, str]: - """Parse a call_matcher path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/conversations/(?P.+?)/callMatchers/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - @staticmethod def conversation_path(project: str, conversation: str,) -> str: """Return a fully-qualified conversation string.""" @@ -747,275 +731,6 @@ def complete_conversation( # Done; return the response. return response - def create_call_matcher( - self, - request: conversation.CreateCallMatcherRequest = None, - *, - parent: str = None, - call_matcher: conversation.CallMatcher = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.CallMatcher: - r"""Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Args: - request (google.cloud.dialogflow_v2.types.CreateCallMatcherRequest): - The request object. The request message for - [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2.Conversations.CreateCallMatcher]. - parent (str): - Required. Resource identifier of the conversation adding - the call matcher. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - call_matcher (google.cloud.dialogflow_v2.types.CallMatcher): - Required. The call matcher to create. - This corresponds to the ``call_matcher`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.types.CallMatcher: - Represents a call matcher that describes criteria for matching incoming SIP - calls to a conversation. When Dialogflow get a SIP - call from a third-party carrier, Dialogflow matches - the call to an existing conversation by either: - - - Extracting the conversation id from the [Call-Info - header](\ https://tools.ietf.org/html/rfc3261#section-20.9), - e.g. Call-Info: - - ;purpose=Goog-ContactCenter-Conversation. - - \* Or, if that doesn't work, matching incoming [SIP - headers](\ https://tools.ietf.org/html/rfc3261#section-7.3) - against any - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] - for the conversation. - - If an incoming SIP call without valid Call-Info - header matches to zero or multiple conversations with - CallMatcher, we reject it. - - A call matcher contains equality conditions for SIP - headers that all have to be fulfilled in order for a - SIP call to match. - - The matched SIP headers consist of well-known headers - (To, From, Call-ID) and custom headers. A - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] - is only valid if it specifies: - - - At least 1 custom header, - - or at least 2 well-known headers. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, call_matcher]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a conversation.CreateCallMatcherRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation.CreateCallMatcherRequest): - request = conversation.CreateCallMatcherRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if call_matcher is not None: - request.call_matcher = call_matcher - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_call_matcher] - - # 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),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_call_matchers( - self, - request: conversation.ListCallMatchersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCallMatchersPager: - r"""Returns the list of all call matchers in the - specified conversation. - - Args: - request (google.cloud.dialogflow_v2.types.ListCallMatchersRequest): - The request object. The request message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. - parent (str): - Required. The conversation to list all call matchers - from. Format: - ``projects//locations//conversations/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2.services.conversations.pagers.ListCallMatchersPager: - The response message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a conversation.ListCallMatchersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation.ListCallMatchersRequest): - request = conversation.ListCallMatchersRequest(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_call_matchers] - - # 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),)), - ) - - # 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.ListCallMatchersPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_call_matcher( - self, - request: conversation.DeleteCallMatcherRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Requests deletion of a call matcher. - - Args: - request (google.cloud.dialogflow_v2.types.DeleteCallMatcherRequest): - The request object. The request message for - [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2.Conversations.DeleteCallMatcher]. - name (str): - Required. The unique identifier of the - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] to - delete. Format: - ``projects//locations//conversations//callMatchers/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a conversation.DeleteCallMatcherRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation.DeleteCallMatcherRequest): - request = conversation.DeleteCallMatcherRequest(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_call_matcher] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - def list_messages( self, request: conversation.ListMessagesRequest = None, diff --git a/google/cloud/dialogflow_v2/services/conversations/pagers.py b/google/cloud/dialogflow_v2/services/conversations/pagers.py index 6e93bdbf6..d770c7e8a 100644 --- a/google/cloud/dialogflow_v2/services/conversations/pagers.py +++ b/google/cloud/dialogflow_v2/services/conversations/pagers.py @@ -158,134 +158,6 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) -class ListCallMatchersPager: - """A pager for iterating through ``list_call_matchers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListCallMatchersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``call_matchers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCallMatchers`` requests and continue to iterate - through the ``call_matchers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListCallMatchersResponse` - 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[..., conversation.ListCallMatchersResponse], - request: conversation.ListCallMatchersRequest, - response: conversation.ListCallMatchersResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListCallMatchersRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListCallMatchersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversation.ListCallMatchersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[conversation.ListCallMatchersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[conversation.CallMatcher]: - for page in self.pages: - yield from page.call_matchers - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListCallMatchersAsyncPager: - """A pager for iterating through ``list_call_matchers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2.types.ListCallMatchersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``call_matchers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCallMatchers`` requests and continue to iterate - through the ``call_matchers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2.types.ListCallMatchersResponse` - 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[conversation.ListCallMatchersResponse]], - request: conversation.ListCallMatchersRequest, - response: conversation.ListCallMatchersResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2.types.ListCallMatchersRequest): - The initial request object. - response (google.cloud.dialogflow_v2.types.ListCallMatchersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversation.ListCallMatchersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[conversation.ListCallMatchersResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[conversation.CallMatcher]: - async def async_generator(): - async for page in self.pages: - for response in page.call_matchers: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - class ListMessagesPager: """A pager for iterating through ``list_messages`` requests. diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/base.py b/google/cloud/dialogflow_v2/services/conversations/transports/base.py index 121fecedf..b96d45a4e 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/base.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/base.py @@ -27,7 +27,6 @@ from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.protobuf import empty_pb2 as empty # type: ignore try: @@ -74,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -94,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -125,15 +124,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - self.create_call_matcher: gapic_v1.method.wrap_method( - self.create_call_matcher, default_timeout=None, client_info=client_info, - ), - self.list_call_matchers: gapic_v1.method.wrap_method( - self.list_call_matchers, default_timeout=None, client_info=client_info, - ), - self.delete_call_matcher: gapic_v1.method.wrap_method( - self.delete_call_matcher, default_timeout=None, client_info=client_info, - ), self.list_messages: gapic_v1.method.wrap_method( self.list_messages, default_timeout=None, client_info=client_info, ), @@ -185,38 +175,6 @@ def complete_conversation( ]: raise NotImplementedError() - @property - def create_call_matcher( - self, - ) -> typing.Callable[ - [conversation.CreateCallMatcherRequest], - typing.Union[ - conversation.CallMatcher, typing.Awaitable[conversation.CallMatcher] - ], - ]: - raise NotImplementedError() - - @property - def list_call_matchers( - self, - ) -> typing.Callable[ - [conversation.ListCallMatchersRequest], - typing.Union[ - conversation.ListCallMatchersResponse, - typing.Awaitable[conversation.ListCallMatchersResponse], - ], - ]: - raise NotImplementedError() - - @property - def delete_call_matcher( - self, - ) -> typing.Callable[ - [conversation.DeleteCallMatcherRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], - ]: - raise NotImplementedError() - @property def list_messages( self, diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py b/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py index 5664521db..f3b8a5578 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py @@ -28,7 +28,6 @@ from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.protobuf import empty_pb2 as empty # type: ignore from .base import ConversationsTransport, DEFAULT_CLIENT_INFO @@ -109,7 +108,9 @@ def __init__( 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) @@ -117,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -212,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -384,89 +356,6 @@ def complete_conversation( ) return self._stubs["complete_conversation"] - @property - def create_call_matcher( - self, - ) -> Callable[[conversation.CreateCallMatcherRequest], conversation.CallMatcher]: - r"""Return a callable for the create call matcher method over gRPC. - - Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Returns: - Callable[[~.CreateCallMatcherRequest], - ~.CallMatcher]: - 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_call_matcher" not in self._stubs: - self._stubs["create_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2.Conversations/CreateCallMatcher", - request_serializer=conversation.CreateCallMatcherRequest.serialize, - response_deserializer=conversation.CallMatcher.deserialize, - ) - return self._stubs["create_call_matcher"] - - @property - def list_call_matchers( - self, - ) -> Callable[ - [conversation.ListCallMatchersRequest], conversation.ListCallMatchersResponse - ]: - r"""Return a callable for the list call matchers method over gRPC. - - Returns the list of all call matchers in the - specified conversation. - - Returns: - Callable[[~.ListCallMatchersRequest], - ~.ListCallMatchersResponse]: - 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_call_matchers" not in self._stubs: - self._stubs["list_call_matchers"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2.Conversations/ListCallMatchers", - request_serializer=conversation.ListCallMatchersRequest.serialize, - response_deserializer=conversation.ListCallMatchersResponse.deserialize, - ) - return self._stubs["list_call_matchers"] - - @property - def delete_call_matcher( - self, - ) -> Callable[[conversation.DeleteCallMatcherRequest], empty.Empty]: - r"""Return a callable for the delete call matcher method over gRPC. - - Requests deletion of a call matcher. - - Returns: - Callable[[~.DeleteCallMatcherRequest], - ~.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_call_matcher" not in self._stubs: - self._stubs["delete_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2.Conversations/DeleteCallMatcher", - request_serializer=conversation.DeleteCallMatcherRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_call_matcher"] - @property def list_messages( self, diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py index 8e0f7f3ed..480cdcfae 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py @@ -29,7 +29,6 @@ from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation -from google.protobuf import empty_pb2 as empty # type: ignore from .base import ConversationsTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationsGrpcTransport @@ -64,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -142,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -154,7 +153,9 @@ def __init__( 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) @@ -162,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -392,92 +364,6 @@ def complete_conversation( ) return self._stubs["complete_conversation"] - @property - def create_call_matcher( - self, - ) -> Callable[ - [conversation.CreateCallMatcherRequest], Awaitable[conversation.CallMatcher] - ]: - r"""Return a callable for the create call matcher method over gRPC. - - Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Returns: - Callable[[~.CreateCallMatcherRequest], - Awaitable[~.CallMatcher]]: - 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_call_matcher" not in self._stubs: - self._stubs["create_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2.Conversations/CreateCallMatcher", - request_serializer=conversation.CreateCallMatcherRequest.serialize, - response_deserializer=conversation.CallMatcher.deserialize, - ) - return self._stubs["create_call_matcher"] - - @property - def list_call_matchers( - self, - ) -> Callable[ - [conversation.ListCallMatchersRequest], - Awaitable[conversation.ListCallMatchersResponse], - ]: - r"""Return a callable for the list call matchers method over gRPC. - - Returns the list of all call matchers in the - specified conversation. - - Returns: - Callable[[~.ListCallMatchersRequest], - Awaitable[~.ListCallMatchersResponse]]: - 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_call_matchers" not in self._stubs: - self._stubs["list_call_matchers"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2.Conversations/ListCallMatchers", - request_serializer=conversation.ListCallMatchersRequest.serialize, - response_deserializer=conversation.ListCallMatchersResponse.deserialize, - ) - return self._stubs["list_call_matchers"] - - @property - def delete_call_matcher( - self, - ) -> Callable[[conversation.DeleteCallMatcherRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete call matcher method over gRPC. - - Requests deletion of a call matcher. - - Returns: - Callable[[~.DeleteCallMatcherRequest], - 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_call_matcher" not in self._stubs: - self._stubs["delete_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2.Conversations/DeleteCallMatcher", - request_serializer=conversation.DeleteCallMatcherRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_call_matcher"] - @property def list_messages( self, diff --git a/google/cloud/dialogflow_v2/services/documents/transports/base.py b/google/cloud/dialogflow_v2/services/documents/transports/base.py index ed8d58937..39425610b 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/base.py @@ -75,10 +75,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -86,6 +86,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -95,20 +98,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/documents/transports/grpc.py b/google/cloud/dialogflow_v2/services/documents/transports/grpc.py index 9f6d6f9ac..e5cb89e6a 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/grpc.py @@ -110,7 +110,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -118,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,18 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py index 0d762777c..105dd3739 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py @@ -65,7 +65,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -143,10 +143,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -155,7 +155,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -163,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/base.py b/google/cloud/dialogflow_v2/services/entity_types/transports/base.py index 40e713587..a2b32c6a1 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py index d8f6831af..cf9544f77 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py @@ -111,7 +111,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,18 +173,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -215,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py index ed7f16d05..7ce05d2e1 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +218,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/environments/transports/base.py b/google/cloud/dialogflow_v2/services/environments/transports/base.py index 3f074dc7f..35fd89eb7 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/base.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/base.py @@ -72,10 +72,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -83,6 +83,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -92,20 +95,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/environments/transports/grpc.py b/google/cloud/dialogflow_v2/services/environments/transports/grpc.py index 0106e187e..fd702da8b 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/grpc.py @@ -107,7 +107,9 @@ def __init__( 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) @@ -115,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -186,17 +168,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -210,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py index 25c848092..f6c738c97 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py @@ -62,7 +62,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -140,10 +140,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -152,7 +152,9 @@ def __init__( 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) @@ -160,70 +162,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -231,17 +213,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/intents/transports/base.py b/google/cloud/dialogflow_v2/services/intents/transports/base.py index 963054bce..57253e26f 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/intents/transports/grpc.py b/google/cloud/dialogflow_v2/services/intents/transports/grpc.py index eda6678ef..605e3f42f 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/grpc.py @@ -110,7 +110,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -118,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,18 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py index 90a158dc9..4c2719a16 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py @@ -65,7 +65,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -143,10 +143,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -155,7 +155,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -163,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py index 9e68503ba..8173590b5 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py @@ -74,10 +74,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,6 +85,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -94,20 +97,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py index 44ec2542a..dd1f16ca4 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py @@ -109,7 +109,9 @@ def __init__( 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) @@ -117,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,17 +170,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -212,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py index 3279f870f..f8372de6a 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py @@ -64,7 +64,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -142,10 +142,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +215,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/participants/async_client.py b/google/cloud/dialogflow_v2/services/participants/async_client.py index ef57c3d3c..beba5d8c1 100644 --- a/google/cloud/dialogflow_v2/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2/services/participants/async_client.py @@ -18,16 +18,7 @@ from collections import OrderedDict import functools import re -from typing import ( - Dict, - AsyncIterable, - Awaitable, - AsyncIterator, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore @@ -517,7 +508,6 @@ async def analyze_content( *, participant: str = None, text_input: session.TextInput = None, - audio_input: gcd_participant.AudioInput = None, event_input: session.EventInput = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -527,8 +517,8 @@ async def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Args: request (:class:`google.cloud.dialogflow_v2.types.AnalyzeContentRequest`): @@ -549,13 +539,6 @@ async def analyze_content( This corresponds to the ``text_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - audio_input (:class:`google.cloud.dialogflow_v2.types.AudioInput`): - The natural language speech audio to - be processed. - - This corresponds to the ``audio_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. event_input (:class:`google.cloud.dialogflow_v2.types.EventInput`): An input event to send to Dialogflow. This corresponds to the ``event_input`` field @@ -577,7 +560,7 @@ async def analyze_content( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, audio_input, event_input]) + has_flattened_params = any([participant, text_input, event_input]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -593,8 +576,6 @@ async def analyze_content( request.participant = participant if text_input is not None: request.text_input = text_input - if audio_input is not None: - request.audio_input = audio_input if event_input is not None: request.event_input = event_input @@ -607,6 +588,7 @@ async def analyze_content( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, @@ -626,109 +608,6 @@ async def analyze_content( # Done; return the response. return response - def streaming_analyze_content( - self, - requests: AsyncIterator[participant.StreamingAnalyzeContentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[participant.StreamingAnalyzeContentResponse]]: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Args: - requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. - However, note that: - - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort - the request stream. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. The next message contains reply_text and - optionally reply_audio returned by an agent. This - message may also contain automated_agent_reply. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_analyze_content, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - async def suggest_articles( self, request: participant.SuggestArticlesRequest = None, diff --git a/google/cloud/dialogflow_v2/services/participants/client.py b/google/cloud/dialogflow_v2/services/participants/client.py index 086d9909c..9500f818f 100644 --- a/google/cloud/dialogflow_v2/services/participants/client.py +++ b/google/cloud/dialogflow_v2/services/participants/client.py @@ -19,17 +19,7 @@ from distutils import util import os import re -from typing import ( - Callable, - Dict, - Optional, - Iterable, - Iterator, - Sequence, - Tuple, - Type, - Union, -) +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -749,7 +739,6 @@ def analyze_content( *, participant: str = None, text_input: session.TextInput = None, - audio_input: gcd_participant.AudioInput = None, event_input: session.EventInput = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -759,8 +748,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Args: request (google.cloud.dialogflow_v2.types.AnalyzeContentRequest): @@ -781,13 +770,6 @@ def analyze_content( This corresponds to the ``text_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - audio_input (google.cloud.dialogflow_v2.types.AudioInput): - The natural language speech audio to - be processed. - - This corresponds to the ``audio_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. event_input (google.cloud.dialogflow_v2.types.EventInput): An input event to send to Dialogflow. This corresponds to the ``event_input`` field @@ -809,7 +791,7 @@ def analyze_content( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, audio_input, event_input]) + has_flattened_params = any([participant, text_input, event_input]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -830,8 +812,6 @@ def analyze_content( request.participant = participant if text_input is not None: request.text_input = text_input - if audio_input is not None: - request.audio_input = audio_input if event_input is not None: request.event_input = event_input @@ -853,107 +833,6 @@ def analyze_content( # Done; return the response. return response - def streaming_analyze_content( - self, - requests: Iterator[participant.StreamingAnalyzeContentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[participant.StreamingAnalyzeContentResponse]: - r"""Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Args: - requests (Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]): - The request object iterator. The top-level message sent by the - client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. - However, note that: - - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort - the request stream. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. The next message contains reply_text and - optionally reply_audio returned by an agent. This - message may also contain automated_agent_reply. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.streaming_analyze_content - ] - - # Send the request. - response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - def suggest_articles( self, request: participant.SuggestArticlesRequest = None, diff --git a/google/cloud/dialogflow_v2/services/participants/transports/base.py b/google/cloud/dialogflow_v2/services/participants/transports/base.py index bf2219e05..357674581 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/base.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -129,15 +129,11 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=client_info, ), - self.streaming_analyze_content: gapic_v1.method.wrap_method( - self.streaming_analyze_content, - default_timeout=220.0, - client_info=client_info, - ), self.suggest_articles: gapic_v1.method.wrap_method( self.suggest_articles, default_timeout=None, client_info=client_info, ), @@ -203,18 +199,6 @@ def analyze_content( ]: raise NotImplementedError() - @property - def streaming_analyze_content( - self, - ) -> typing.Callable[ - [participant.StreamingAnalyzeContentRequest], - typing.Union[ - participant.StreamingAnalyzeContentResponse, - typing.Awaitable[participant.StreamingAnalyzeContentResponse], - ], - ]: - raise NotImplementedError() - @property def suggest_articles( self, diff --git a/google/cloud/dialogflow_v2/services/participants/transports/grpc.py b/google/cloud/dialogflow_v2/services/participants/transports/grpc.py index 386acf35f..e4543e6bf 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/grpc.py @@ -108,7 +108,9 @@ def __init__( 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) @@ -116,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -187,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -211,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -373,8 +346,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Returns: Callable[[~.AnalyzeContentRequest], @@ -394,50 +367,6 @@ def analyze_content( ) return self._stubs["analyze_content"] - @property - def streaming_analyze_content( - self, - ) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - participant.StreamingAnalyzeContentResponse, - ]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - ~.StreamingAnalyzeContentResponse]: - 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 "streaming_analyze_content" not in self._stubs: - self._stubs["streaming_analyze_content"] = self.grpc_channel.stream_stream( - "/google.cloud.dialogflow.v2.Participants/StreamingAnalyzeContent", - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs["streaming_analyze_content"] - @property def suggest_articles( self, diff --git a/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py index b00793e84..78dc60b4b 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py @@ -63,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -141,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -153,7 +153,9 @@ def __init__( 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) @@ -161,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -232,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -383,8 +356,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Returns: Callable[[~.AnalyzeContentRequest], @@ -404,50 +377,6 @@ def analyze_content( ) return self._stubs["analyze_content"] - @property - def streaming_analyze_content( - self, - ) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - Awaitable[participant.StreamingAnalyzeContentResponse], - ]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (chat, for example), or audio (phone recording, for - example) message from a participant into the conversation. Note: - This method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field and potentially the - ``reply_audio`` field. The message can also contain the - ``automated_agent_reply`` field. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - Awaitable[~.StreamingAnalyzeContentResponse]]: - 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 "streaming_analyze_content" not in self._stubs: - self._stubs["streaming_analyze_content"] = self.grpc_channel.stream_stream( - "/google.cloud.dialogflow.v2.Participants/StreamingAnalyzeContent", - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs["streaming_analyze_content"] - @property def suggest_articles( self, diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py index 67a27daff..529860533 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py index 9c59bc921..d68070365 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py @@ -111,7 +111,9 @@ def __init__( 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) @@ -119,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,17 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py index 7f8d60544..feaffcd71 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/services/sessions/async_client.py b/google/cloud/dialogflow_v2/services/sessions/async_client.py index 5107f62c4..e479f1bce 100644 --- a/google/cloud/dialogflow_v2/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2/services/sessions/async_client.py @@ -289,6 +289,7 @@ async def detect_intent( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/base.py b/google/cloud/dialogflow_v2/services/sessions/transports/base.py index c29e65fe1..4441c222d 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/base.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -117,6 +117,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=client_info, diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py b/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py index a1453406e..995202acf 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py @@ -110,7 +110,9 @@ def __init__( 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) @@ -118,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,17 +171,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -213,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py index fe8954714..69689dd2a 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py @@ -65,7 +65,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -143,10 +143,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -155,7 +155,9 @@ def __init__( 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) @@ -163,70 +165,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,17 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2/types/__init__.py b/google/cloud/dialogflow_v2/types/__init__.py index 8b850081c..ba48aa9da 100644 --- a/google/cloud/dialogflow_v2/types/__init__.py +++ b/google/cloud/dialogflow_v2/types/__init__.py @@ -45,13 +45,11 @@ SpeechToTextConfig, SpeechWordInfo, SynthesizeSpeechConfig, - TelephonyDtmfEvents, VoiceSelectionParams, AudioEncoding, OutputAudioEncoding, SpeechModelVariant, SsmlVoiceGender, - TelephonyDtmf, ) from .context import ( Context, @@ -64,16 +62,11 @@ UpdateContextRequest, ) from .conversation import ( - CallMatcher, CompleteConversationRequest, Conversation, ConversationPhoneNumber, - CreateCallMatcherRequest, CreateConversationRequest, - DeleteCallMatcherRequest, GetConversationRequest, - ListCallMatchersRequest, - ListCallMatchersResponse, ListConversationsRequest, ListConversationsResponse, ListMessagesRequest, @@ -156,21 +149,17 @@ AnalyzeContentResponse, AnnotatedMessagePart, ArticleAnswer, - AudioInput, AutomatedAgentReply, CreateParticipantRequest, DtmfParameters, FaqAnswer, GetParticipantRequest, - InputTextConfig, ListParticipantsRequest, ListParticipantsResponse, Message, MessageAnnotation, OutputAudio, Participant, - StreamingAnalyzeContentRequest, - StreamingAnalyzeContentResponse, SuggestArticlesRequest, SuggestArticlesResponse, SuggestFaqAnswersRequest, @@ -238,13 +227,11 @@ "SpeechToTextConfig", "SpeechWordInfo", "SynthesizeSpeechConfig", - "TelephonyDtmfEvents", "VoiceSelectionParams", "AudioEncoding", "OutputAudioEncoding", "SpeechModelVariant", "SsmlVoiceGender", - "TelephonyDtmf", "Context", "CreateContextRequest", "DeleteAllContextsRequest", @@ -253,16 +240,11 @@ "ListContextsRequest", "ListContextsResponse", "UpdateContextRequest", - "CallMatcher", "CompleteConversationRequest", "Conversation", "ConversationPhoneNumber", - "CreateCallMatcherRequest", "CreateConversationRequest", - "DeleteCallMatcherRequest", "GetConversationRequest", - "ListCallMatchersRequest", - "ListCallMatchersResponse", "ListConversationsRequest", "ListConversationsResponse", "ListMessagesRequest", @@ -331,21 +313,17 @@ "AnalyzeContentResponse", "AnnotatedMessagePart", "ArticleAnswer", - "AudioInput", "AutomatedAgentReply", "CreateParticipantRequest", "DtmfParameters", "FaqAnswer", "GetParticipantRequest", - "InputTextConfig", "ListParticipantsRequest", "ListParticipantsResponse", "Message", "MessageAnnotation", "OutputAudio", "Participant", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "SuggestArticlesRequest", "SuggestArticlesResponse", "SuggestFaqAnswersRequest", diff --git a/google/cloud/dialogflow_v2/types/audio_config.py b/google/cloud/dialogflow_v2/types/audio_config.py index 83d724e1d..4b8ecf6d8 100644 --- a/google/cloud/dialogflow_v2/types/audio_config.py +++ b/google/cloud/dialogflow_v2/types/audio_config.py @@ -28,14 +28,12 @@ "SpeechModelVariant", "SsmlVoiceGender", "OutputAudioEncoding", - "TelephonyDtmf", "SpeechContext", "SpeechWordInfo", "InputAudioConfig", "VoiceSelectionParams", "SynthesizeSpeechConfig", "OutputAudioConfig", - "TelephonyDtmfEvents", "SpeechToTextConfig", }, ) @@ -89,30 +87,9 @@ class OutputAudioEncoding(proto.Enum): OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 OUTPUT_AUDIO_ENCODING_MP3 = 2 + OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 - - -class TelephonyDtmf(proto.Enum): - r"""`DTMF `__ - digit in Telephony Gateway. - """ - TELEPHONY_DTMF_UNSPECIFIED = 0 - DTMF_ONE = 1 - DTMF_TWO = 2 - DTMF_THREE = 3 - DTMF_FOUR = 4 - DTMF_FIVE = 5 - DTMF_SIX = 6 - DTMF_SEVEN = 7 - DTMF_EIGHT = 8 - DTMF_NINE = 9 - DTMF_ZERO = 10 - DTMF_A = 11 - DTMF_B = 12 - DTMF_C = 13 - DTMF_D = 14 - DTMF_STAR = 15 - DTMF_POUND = 16 + OUTPUT_AUDIO_ENCODING_MULAW = 5 class SpeechContext(proto.Message): @@ -404,17 +381,6 @@ class OutputAudioConfig(proto.Message): ) -class TelephonyDtmfEvents(proto.Message): - r"""A wrapper of repeated TelephonyDtmf digits. - - Attributes: - dtmf_events (Sequence[google.cloud.dialogflow_v2.types.TelephonyDtmf]): - A sequence of TelephonyDtmf digits. - """ - - dtmf_events = proto.RepeatedField(proto.ENUM, number=1, enum="TelephonyDtmf",) - - class SpeechToTextConfig(proto.Message): r"""Configures speech transcription for [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile]. diff --git a/google/cloud/dialogflow_v2/types/conversation.py b/google/cloud/dialogflow_v2/types/conversation.py index 7548e1730..a53db5ebe 100644 --- a/google/cloud/dialogflow_v2/types/conversation.py +++ b/google/cloud/dialogflow_v2/types/conversation.py @@ -26,16 +26,11 @@ package="google.cloud.dialogflow.v2", manifest={ "Conversation", - "CallMatcher", "CreateConversationRequest", "ListConversationsRequest", "ListConversationsResponse", "GetConversationRequest", "CompleteConversationRequest", - "CreateCallMatcherRequest", - "ListCallMatchersRequest", - "ListCallMatchersResponse", - "DeleteCallMatcherRequest", "ListMessagesRequest", "ListMessagesResponse", "ConversationPhoneNumber", @@ -124,85 +119,6 @@ class ConversationStage(proto.Enum): conversation_stage = proto.Field(proto.ENUM, number=7, enum=ConversationStage,) -class CallMatcher(proto.Message): - r"""Represents a call matcher that describes criteria for matching - incoming SIP calls to a conversation. When Dialogflow get a SIP call - from a third-party carrier, Dialogflow matches the call to an - existing conversation by either: - - - Extracting the conversation id from the `Call-Info - header `__, - e.g. - ``Call-Info: ;purpose=Goog-ContactCenter-Conversation``. - - Or, if that doesn't work, matching incoming `SIP - headers `__ - against any [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] - for the conversation. - - If an incoming SIP call without valid ``Call-Info`` header matches - to zero or multiple conversations with ``CallMatcher``, we reject - it. - - A call matcher contains equality conditions for SIP headers that all - have to be fulfilled in order for a SIP call to match. - - The matched SIP headers consist of well-known headers (``To``, - ``From``, ``Call-ID``) and custom headers. A - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] is only valid - if it specifies: - - - At least 1 custom header, - - or at least 2 well-known headers. - - Attributes: - name (str): - Output only. The unique identifier of this call matcher. - Format: - ``projects//locations//conversations//callMatchers/``. - to_header (str): - Value of the ```To`` - header `__ - to match. If empty or unspecified, we don't match to the - ```To`` - header `__. - from_header (str): - Value of the ```From`` - header `__ - to match. If empty or unspecified, we don't match to the - ```From`` - header `__. - call_id_header (str): - Value of the ```Call-ID`` - header `__ - to match. If empty or unspecified, we don't match to the - ```Call-ID`` - header `__. - custom_headers (google.cloud.dialogflow_v2.types.CallMatcher.CustomHeaders): - Custom SIP headers that must match. - """ - - class CustomHeaders(proto.Message): - r"""Custom SIP headers. See the `description of headers in the - RFC `__. - - Attributes: - cisco_guid (str): - Cisco's proprietary ``Cisco-Guid`` header. - """ - - cisco_guid = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - to_header = proto.Field(proto.STRING, number=2) - - from_header = proto.Field(proto.STRING, number=3) - - call_id_header = proto.Field(proto.STRING, number=4) - - custom_headers = proto.Field(proto.MESSAGE, number=5, message=CustomHeaders,) - - class CreateConversationRequest(proto.Message): r"""The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. @@ -337,86 +253,6 @@ class CompleteConversationRequest(proto.Message): name = proto.Field(proto.STRING, number=1) -class CreateCallMatcherRequest(proto.Message): - r"""The request message for - [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2.Conversations.CreateCallMatcher]. - - Attributes: - parent (str): - Required. Resource identifier of the conversation adding the - call matcher. Format: - ``projects//locations//conversations/``. - call_matcher (google.cloud.dialogflow_v2.types.CallMatcher): - Required. The call matcher to create. - """ - - parent = proto.Field(proto.STRING, number=1) - - call_matcher = proto.Field(proto.MESSAGE, number=2, message="CallMatcher",) - - -class ListCallMatchersRequest(proto.Message): - r"""The request message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. - - Attributes: - parent (str): - Required. The conversation to list all call matchers from. - Format: - ``projects//locations//conversations/``. - page_size (int): - Optional. The maximum number of items to - return in a single page. By default 100 and at - most 1000. - page_token (str): - Optional. The next_page_token value returned from a previous - list request. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListCallMatchersResponse(proto.Message): - r"""The response message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2.Conversations.ListCallMatchers]. - - Attributes: - call_matchers (Sequence[google.cloud.dialogflow_v2.types.CallMatcher]): - The list of call matchers. There is a maximum number of - items returned based on the page_size field in the request. - next_page_token (str): - Token to retrieve the next page of results or - empty if there are no more results in the list. - """ - - @property - def raw_page(self): - return self - - call_matchers = proto.RepeatedField(proto.MESSAGE, number=1, message="CallMatcher",) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class DeleteCallMatcherRequest(proto.Message): - r"""The request message for - [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2.Conversations.DeleteCallMatcher]. - - Attributes: - name (str): - Required. The unique identifier of the - [CallMatcher][google.cloud.dialogflow.v2.CallMatcher] to - delete. Format: - ``projects//locations//conversations//callMatchers/``. - """ - - name = proto.Field(proto.STRING, number=1) - - class ListMessagesRequest(proto.Message): r"""The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. diff --git a/google/cloud/dialogflow_v2/types/participant.py b/google/cloud/dialogflow_v2/types/participant.py index 1be79ddc0..e965b4a09 100644 --- a/google/cloud/dialogflow_v2/types/participant.py +++ b/google/cloud/dialogflow_v2/types/participant.py @@ -18,7 +18,7 @@ import proto # type: ignore -from google.cloud.dialogflow_v2.types import audio_config as gcd_audio_config +from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import struct_pb2 as struct # type: ignore @@ -39,19 +39,15 @@ "AnalyzeContentRequest", "DtmfParameters", "AnalyzeContentResponse", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "SuggestArticlesRequest", "SuggestArticlesResponse", "SuggestFaqAnswersRequest", "SuggestFaqAnswersResponse", - "AudioInput", "OutputAudio", "AutomatedAgentReply", "ArticleAnswer", "FaqAnswer", "SuggestionResult", - "InputTextConfig", "AnnotatedMessagePart", "MessageAnnotation", }, @@ -242,9 +238,6 @@ class AnalyzeContentRequest(proto.Message): ``projects//locations//conversations//participants/``. text_input (google.cloud.dialogflow_v2.types.TextInput): The natural language text to be processed. - audio_input (google.cloud.dialogflow_v2.types.AudioInput): - The natural language speech audio to be - processed. event_input (google.cloud.dialogflow_v2.types.EventInput): An input event to send to Dialogflow. reply_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): @@ -269,16 +262,12 @@ class AnalyzeContentRequest(proto.Message): proto.MESSAGE, number=6, oneof="input", message=session.TextInput, ) - audio_input = proto.Field( - proto.MESSAGE, number=7, oneof="input", message="AudioInput", - ) - event_input = proto.Field( proto.MESSAGE, number=8, oneof="input", message=session.EventInput, ) reply_audio_config = proto.Field( - proto.MESSAGE, number=5, message=gcd_audio_config.OutputAudioConfig, + proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) query_params = proto.Field( @@ -369,203 +358,6 @@ class AnalyzeContentResponse(proto.Message): dtmf_parameters = proto.Field(proto.MESSAGE, number=9, message="DtmfParameters",) -class StreamingAnalyzeContentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also contain - [reply_audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. However, note that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results in favor of - the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort the request - stream. - - Attributes: - participant (str): - Required. The name of the participant this text comes from. - Format: - ``projects//locations//conversations//participants/``. - audio_config (google.cloud.dialogflow_v2.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - text_config (google.cloud.dialogflow_v2.types.InputTextConfig): - The natural language text to be processed. - reply_audio_config (google.cloud.dialogflow_v2.types.OutputAudioConfig): - Speech synthesis configuration. - The speech synthesis settings for a virtual - agent that may be configured for the associated - conversation profile are not used when calling - StreamingAnalyzeContent. If this configuration - is not supplied, speech synthesis is disabled. - input_audio (bytes): - The input audio content to be recognized. Must be sent if - ``audio_config`` is set in the first message. The complete - audio over all streaming messages must not exceed 1 minute. - input_text (str): - The UTF-8 encoded natural language text to be processed. - Must be sent if ``text_config`` is set in the first message. - Text length must not exceed 256 bytes. The ``input_text`` - field can be only sent once. - input_dtmf (google.cloud.dialogflow_v2.types.TelephonyDtmfEvents): - The DTMF digits used to invoke intent and - fill in parameter value. - This input is ignored if the previous response - indicated that DTMF input is not accepted. - query_params (google.cloud.dialogflow_v2.types.QueryParameters): - Parameters for a Dialogflow virtual-agent - query. - """ - - participant = proto.Field(proto.STRING, number=1) - - audio_config = proto.Field( - proto.MESSAGE, - number=2, - oneof="config", - message=gcd_audio_config.InputAudioConfig, - ) - - text_config = proto.Field( - proto.MESSAGE, number=3, oneof="config", message="InputTextConfig", - ) - - reply_audio_config = proto.Field( - proto.MESSAGE, number=4, message=gcd_audio_config.OutputAudioConfig, - ) - - input_audio = proto.Field(proto.BYTES, number=5, oneof="input") - - input_text = proto.Field(proto.STRING, number=6, oneof="input") - - input_dtmf = proto.Field( - proto.MESSAGE, - number=9, - oneof="input", - message=gcd_audio_config.TelephonyDtmfEvents, - ) - - query_params = proto.Field( - proto.MESSAGE, number=7, message=session.QueryParameters, - ) - - -class StreamingAnalyzeContentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingAnalyzeContent`` - method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first one or more - messages contain ``recognition_result``. Each - ``recognition_result`` represents a more complete transcript of - what the user said. The last ``recognition_result`` has - ``is_final`` set to ``true``. - - 2. The next message contains ``reply_text`` and optionally - ``reply_audio`` returned by an agent. This message may also - contain ``automated_agent_reply``. - - Attributes: - recognition_result (google.cloud.dialogflow_v2.types.StreamingRecognitionResult): - The result of speech recognition. - reply_text (str): - The output text content. - This field is set if an automated agent - responded with a text for the user. - reply_audio (google.cloud.dialogflow_v2.types.OutputAudio): - The audio data bytes encoded as specified in the request. - This field is set if: - - - The ``reply_audio_config`` field is specified in the - request. - - The automated agent, which this output comes from, - responded with audio. In such case, the - ``reply_audio.config`` field contains settings used to - synthesize the speech. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - automated_agent_reply (google.cloud.dialogflow_v2.types.AutomatedAgentReply): - Only set if a Dialogflow automated agent has responded. Note - that: - [AutomatedAgentReply.detect_intent_response.output_audio][] - and - [AutomatedAgentReply.detect_intent_response.output_audio_config][] - are always empty, use - [reply_audio][google.cloud.dialogflow.v2.StreamingAnalyzeContentResponse.reply_audio] - instead. - message (google.cloud.dialogflow_v2.types.Message): - Message analyzed by CCAI. - human_agent_suggestion_results (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestions for most recent human agent. The order is - the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.human_agent_suggestion_config]. - end_user_suggestion_results (Sequence[google.cloud.dialogflow_v2.types.SuggestionResult]): - The suggestions for end user. The order is the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.end_user_suggestion_config]. - dtmf_parameters (google.cloud.dialogflow_v2.types.DtmfParameters): - Indicates the parameters of DTMF. - """ - - recognition_result = proto.Field( - proto.MESSAGE, number=1, message=session.StreamingRecognitionResult, - ) - - reply_text = proto.Field(proto.STRING, number=2) - - reply_audio = proto.Field(proto.MESSAGE, number=3, message="OutputAudio",) - - automated_agent_reply = proto.Field( - proto.MESSAGE, number=4, message="AutomatedAgentReply", - ) - - message = proto.Field(proto.MESSAGE, number=6, message="Message",) - - human_agent_suggestion_results = proto.RepeatedField( - proto.MESSAGE, number=7, message="SuggestionResult", - ) - - end_user_suggestion_results = proto.RepeatedField( - proto.MESSAGE, number=8, message="SuggestionResult", - ) - - dtmf_parameters = proto.Field(proto.MESSAGE, number=10, message="DtmfParameters",) - - class SuggestArticlesRequest(proto.Message): r"""The request message for [Participants.SuggestArticles][google.cloud.dialogflow.v2.Participants.SuggestArticles]. @@ -686,28 +478,6 @@ class SuggestFaqAnswersResponse(proto.Message): context_size = proto.Field(proto.INT32, number=3) -class AudioInput(proto.Message): - r"""Represents the natural language speech audio to be processed. - - Attributes: - config (google.cloud.dialogflow_v2.types.InputAudioConfig): - Required. Instructs the speech recognizer how - to process the speech audio. - audio (bytes): - Required. The natural language speech audio - to be processed. A single request can contain up - to 1 minute of speech audio data. The - transcribed text cannot contain more than 256 - bytes. - """ - - config = proto.Field( - proto.MESSAGE, number=1, message=gcd_audio_config.InputAudioConfig, - ) - - audio = proto.Field(proto.BYTES, number=2) - - class OutputAudio(proto.Message): r"""Represents the natural language speech audio to be played to the end user. @@ -721,7 +491,7 @@ class OutputAudio(proto.Message): """ config = proto.Field( - proto.MESSAGE, number=1, message=gcd_audio_config.OutputAudioConfig, + proto.MESSAGE, number=1, message=audio_config.OutputAudioConfig, ) audio = proto.Field(proto.BYTES, number=2) @@ -858,20 +628,6 @@ class SuggestionResult(proto.Message): ) -class InputTextConfig(proto.Message): - r"""Defines the language used in the input text. - - Attributes: - language_code (str): - Required. The language of this conversational query. See - `Language - Support `__ - for a list of the currently supported language codes. - """ - - language_code = proto.Field(proto.STRING, number=1) - - class AnnotatedMessagePart(proto.Message): r"""Represents a part of a message possibly annotated with an entity. The part can be an entity or purely a part of the diff --git a/google/cloud/dialogflow_v2beta1/__init__.py b/google/cloud/dialogflow_v2beta1/__init__.py index 22d347629..64c30902f 100644 --- a/google/cloud/dialogflow_v2beta1/__init__.py +++ b/google/cloud/dialogflow_v2beta1/__init__.py @@ -72,17 +72,12 @@ from .types.context import UpdateContextRequest from .types.conversation import BatchCreateMessagesRequest from .types.conversation import BatchCreateMessagesResponse -from .types.conversation import CallMatcher from .types.conversation import CompleteConversationRequest from .types.conversation import Conversation from .types.conversation import ConversationPhoneNumber -from .types.conversation import CreateCallMatcherRequest from .types.conversation import CreateConversationRequest from .types.conversation import CreateMessageRequest -from .types.conversation import DeleteCallMatcherRequest from .types.conversation import GetConversationRequest -from .types.conversation import ListCallMatchersRequest -from .types.conversation import ListCallMatchersResponse from .types.conversation import ListConversationsRequest from .types.conversation import ListConversationsResponse from .types.conversation import ListMessagesRequest @@ -155,7 +150,6 @@ from .types.participant import AnalyzeContentResponse from .types.participant import AnnotatedMessagePart from .types.participant import ArticleAnswer -from .types.participant import AudioInput from .types.participant import AutomatedAgentReply from .types.participant import CompileSuggestionRequest from .types.participant import CompileSuggestionResponse @@ -165,7 +159,6 @@ from .types.participant import GetParticipantRequest from .types.participant import InputAudio from .types.participant import InputText -from .types.participant import InputTextConfig from .types.participant import ListParticipantsRequest from .types.participant import ListParticipantsResponse from .types.participant import ListSuggestionsRequest @@ -176,8 +169,6 @@ from .types.participant import Participant from .types.participant import ResponseMessage from .types.participant import SmartReplyAnswer -from .types.participant import StreamingAnalyzeContentRequest -from .types.participant import StreamingAnalyzeContentResponse from .types.participant import SuggestArticlesRequest from .types.participant import SuggestArticlesResponse from .types.participant import SuggestFaqAnswersRequest @@ -229,7 +220,6 @@ "AnswerRecordsClient", "ArticleAnswer", "AudioEncoding", - "AudioInput", "AutomatedAgentConfig", "AutomatedAgentReply", "BatchCreateEntitiesRequest", @@ -243,7 +233,6 @@ "BatchUpdateEntityTypesResponse", "BatchUpdateIntentsRequest", "BatchUpdateIntentsResponse", - "CallMatcher", "CompileSuggestionRequest", "CompileSuggestionResponse", "CompleteConversationRequest", @@ -255,7 +244,6 @@ "ConversationProfile", "ConversationProfilesClient", "ConversationsClient", - "CreateCallMatcherRequest", "CreateContextRequest", "CreateConversationProfileRequest", "CreateConversationRequest", @@ -268,7 +256,6 @@ "CreateSessionEntityTypeRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", - "DeleteCallMatcherRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", @@ -314,18 +301,15 @@ "InputAudio", "InputAudioConfig", "InputText", - "InputTextConfig", "Intent", "IntentBatch", "IntentView", + "IntentsClient", "KnowledgeAnswers", "KnowledgeBase", - "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", - "ListCallMatchersRequest", - "ListCallMatchersResponse", "ListContextsRequest", "ListContextsResponse", "ListConversationProfilesRequest", @@ -381,8 +365,6 @@ "SpeechToTextConfig", "SpeechWordInfo", "SsmlVoiceGender", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", @@ -415,5 +397,5 @@ "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "IntentsClient", + "KnowledgeBasesClient", ) diff --git a/google/cloud/dialogflow_v2beta1/proto/answer_record.proto b/google/cloud/dialogflow_v2beta1/proto/answer_record.proto index b344010d1..4f7b9f44a 100644 --- a/google/cloud/dialogflow_v2beta1/proto/answer_record.proto +++ b/google/cloud/dialogflow_v2beta1/proto/answer_record.proto @@ -33,7 +33,8 @@ option java_outer_classname = "AnswerRecordsProto"; option java_package = "com.google.cloud.dialogflow.v2beta1"; option objc_class_prefix = "DF"; -// Service for managing [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. +// Service for managing +// [AnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecord]. service AnswerRecords { option (google.api.default_host) = "dialogflow.googleapis.com"; option (google.api.oauth_scopes) = @@ -54,7 +55,8 @@ service AnswerRecords { // Returns the list of all answer records in the specified project in reverse // chronological order. - rpc ListAnswerRecords(ListAnswerRecordsRequest) returns (ListAnswerRecordsResponse) { + rpc ListAnswerRecords(ListAnswerRecordsRequest) + returns (ListAnswerRecordsResponse) { option (google.api.http) = { get: "/v2beta1/{parent=projects/*}/answerRecords" additional_bindings { @@ -99,9 +101,12 @@ service AnswerRecords { // A typical workflow for customers provide feedback to an answer is: // // 1. For human agent assistant, customers get suggestion via ListSuggestions -// API. Together with the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the -// customers. -// 2. The customer uses the [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] to call the +// API. Together with the answers, +// [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are +// returned to the customers. +// 2. The customer uses the +// [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] to +// call the // [UpdateAnswerRecord][] method to send feedback about a specific answer // that they believe is wrong. message AnswerRecord { @@ -112,14 +117,15 @@ message AnswerRecord { }; // The unique identifier of this answer record. - // Required for [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] method. - // Format: `projects//locations//locations//answerRecords/`. string name = 1; // Optional. The AnswerFeedback for this record. You can set this with - // [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] in order to give us feedback about - // this answer. + // [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord] + // in order to give us feedback about this answer. AnswerFeedback answer_feedback = 3; // Output only. The record for this answer. @@ -134,7 +140,8 @@ message AgentAssistantRecord { // Output only. The agent assistant answer. oneof answer { // Output only. The article suggestion answer. - ArticleAnswer article_suggestion_answer = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + ArticleAnswer article_suggestion_answer = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; // Output only. The FAQ answer. FaqAnswer faq_answer = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; @@ -256,7 +263,9 @@ message AgentAssistantFeedback { // Optional. Whether or not the suggested document is efficient. For example, // if the document is poorly written, hard to understand, hard to use or - // too long to find useful information, [document_efficiency][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.document_efficiency] is + // too long to find useful information, + // [document_efficiency][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.document_efficiency] + // is // [DocumentEfficiency.INEFFICIENT][google.cloud.dialogflow.v2beta1.AgentAssistantFeedback.DocumentEfficiency.INEFFICIENT]. DocumentEfficiency document_efficiency = 3; @@ -264,7 +273,8 @@ message AgentAssistantFeedback { SummarizationFeedback summarization_feedback = 4; } -// Request message for [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. +// Request message for +// [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. message GetAnswerRecordRequest { // Required. The name of the answer record to retrieve. // Format: `projects//locations//locations/`. string parent = 1 [(google.api.resource_reference) = { - child_type: "dialogflow.googleapis.com/AnswerRecord" - }]; + child_type: "dialogflow.googleapis.com/AnswerRecord" + }]; // Optional. The maximum number of records to return in a single page. // The server may return fewer records than this. If unspecified, we use 10. @@ -293,7 +304,8 @@ message ListAnswerRecordsRequest { string page_token = 4; } -// Response message for [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. +// Response message for +// [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. message ListAnswerRecordsResponse { // The list of answer records. repeated AnswerRecord answer_records = 1; @@ -307,15 +319,11 @@ message ListAnswerRecordsResponse { string next_page_token = 2; } -// Request message for [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. +// Request message for +// [AnswerRecords.UpdateAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.UpdateAnswerRecord]. message UpdateAnswerRecordRequest { // Required. Answer record to update. - AnswerRecord answer_record = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/AnswerRecord" - } - ]; + AnswerRecord answer_record = 1 [(google.api.field_behavior) = REQUIRED]; // Required. The mask to control which fields get updated. google.protobuf.FieldMask update_mask = 2; diff --git a/google/cloud/dialogflow_v2beta1/proto/audio_config.proto b/google/cloud/dialogflow_v2beta1/proto/audio_config.proto index 009a9473b..f8c42b7db 100644 --- a/google/cloud/dialogflow_v2beta1/proto/audio_config.proto +++ b/google/cloud/dialogflow_v2beta1/proto/audio_config.proto @@ -359,11 +359,17 @@ enum OutputAudioEncoding { // MP3 audio at 32kbps. OUTPUT_AUDIO_ENCODING_MP3 = 2; + // MP3 audio at 64kbps. + OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4; + // Opus encoded audio wrapped in an ogg container. The result will be a // file which can be played natively on Android, and in browsers (at least // Chrome and Firefox). The quality of the encoding is considerably higher // than MP3 while using approximately the same bitrate. OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3; + + // 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. + OUTPUT_AUDIO_ENCODING_MULAW = 5; } // Configures speech transcription for [ConversationProfile][google.cloud.dialogflow.v2beta1.ConversationProfile]. diff --git a/google/cloud/dialogflow_v2beta1/proto/conversation.proto b/google/cloud/dialogflow_v2beta1/proto/conversation.proto index 068473823..6e203540b 100644 --- a/google/cloud/dialogflow_v2beta1/proto/conversation.proto +++ b/google/cloud/dialogflow_v2beta1/proto/conversation.proto @@ -37,7 +37,8 @@ option java_outer_classname = "ConversationProto"; option java_package = "com.google.cloud.dialogflow.v2beta1"; option objc_class_prefix = "DF"; -// Service for managing [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. +// Service for managing +// [Conversations][google.cloud.dialogflow.v2beta1.Conversation]. service Conversations { option (google.api.default_host) = "dialogflow.googleapis.com"; option (google.api.oauth_scopes) = @@ -57,11 +58,14 @@ service Conversations { // For Assist Stage, there's no dialogflow agent responding to user queries. // But we will provide suggestions which are generated from conversation. // - // If [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] is configured for a dialogflow - // agent, conversation will start from `Automated Agent Stage`, otherwise, it - // will start from `Assist Stage`. And during `Automated Agent Stage`, once an - // [Intent][google.cloud.dialogflow.v2beta1.Intent] with [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] is triggered, conversation - // will transfer to Assist Stage. + // If + // [Conversation.conversation_profile][google.cloud.dialogflow.v2beta1.Conversation.conversation_profile] + // is configured for a dialogflow agent, conversation will start from + // `Automated Agent Stage`, otherwise, it will start from `Assist Stage`. And + // during `Automated Agent Stage`, once an + // [Intent][google.cloud.dialogflow.v2beta1.Intent] with + // [Intent.live_agent_handoff][google.cloud.dialogflow.v2beta1.Intent.live_agent_handoff] + // is triggered, conversation will transfer to Assist Stage. rpc CreateConversation(CreateConversationRequest) returns (Conversation) { option (google.api.http) = { post: "/v2beta1/{parent=projects/*}/conversations" @@ -75,7 +79,8 @@ service Conversations { } // Returns the list of all conversations in the specified project. - rpc ListConversations(ListConversationsRequest) returns (ListConversationsResponse) { + rpc ListConversations(ListConversationsRequest) + returns (ListConversationsResponse) { option (google.api.http) = { get: "/v2beta1/{parent=projects/*}/conversations" additional_bindings { @@ -110,45 +115,10 @@ service Conversations { option (google.api.method_signature) = "name"; } - // Creates a call matcher that links incoming SIP calls to the specified - // conversation if they fulfill specified criteria. - rpc CreateCallMatcher(CreateCallMatcherRequest) returns (CallMatcher) { - option (google.api.http) = { - post: "/v2beta1/{parent=projects/*/conversations/*}/callMatchers" - body: "call_matcher" - additional_bindings { - post: "/v2beta1/{parent=projects/*/locations/*/conversations/*}/callMatchers" - body: "*" - } - }; - option (google.api.method_signature) = "parent,call_matcher"; - } - - // Returns the list of all call matchers in the specified conversation. - rpc ListCallMatchers(ListCallMatchersRequest) returns (ListCallMatchersResponse) { - option (google.api.http) = { - get: "/v2beta1/{parent=projects/*/conversations/*}/callMatchers" - additional_bindings { - get: "/v2beta1/{parent=projects/*/locations/*/conversations/*}/callMatchers" - } - }; - option (google.api.method_signature) = "parent"; - } - - // Requests deletion of a call matcher. - rpc DeleteCallMatcher(DeleteCallMatcherRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v2beta1/{name=projects/*/conversations/*/callMatchers/*}" - additional_bindings { - delete: "/v2beta1/{name=projects/*/locations/*/conversations/*/callMatchers/*}" - } - }; - option (google.api.method_signature) = "name"; - } - // Batch ingests messages to conversation. Customers can use this RPC to // ingest historical messages to conversation. - rpc BatchCreateMessages(BatchCreateMessagesRequest) returns (BatchCreateMessagesResponse) { + rpc BatchCreateMessages(BatchCreateMessagesRequest) + returns (BatchCreateMessagesResponse) { option (google.api.http) = { post: "/v2beta1/{parent=projects/*/conversations/*}/messages:batchCreate" body: "*" @@ -222,7 +192,8 @@ message Conversation { string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; // Output only. The current state of the Conversation. - LifecycleState lifecycle_state = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + LifecycleState lifecycle_state = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; // Required. The Conversation Profile to be used to configure this // Conversation. This field cannot be updated. @@ -237,28 +208,34 @@ message Conversation { // Output only. Required if the conversation is to be connected over // telephony. - ConversationPhoneNumber phone_number = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + ConversationPhoneNumber phone_number = 4 + [(google.api.field_behavior) = OUTPUT_ONLY]; // The stage of a conversation. It indicates whether the virtual agent or a // human agent is handling the conversation. // // If the conversation is created with the conversation profile that has // Dialogflow config set, defaults to - // [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE]; Otherwise, defaults to + // [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE]; + // Otherwise, defaults to // [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. // // If the conversation is created with the conversation profile that has // Dialogflow config set but explicitly sets conversation_stage to - // [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE], it skips - // [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE] stage and directly goes to + // [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE], + // it skips + // [ConversationStage.VIRTUAL_AGENT_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE] + // stage and directly goes to // [ConversationStage.HUMAN_ASSIST_STAGE][google.cloud.dialogflow.v2beta1.Conversation.ConversationStage.HUMAN_ASSIST_STAGE]. ConversationStage conversation_stage = 7; // Output only. The time the conversation was started. - google.protobuf.Timestamp start_time = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + google.protobuf.Timestamp start_time = 5 + [(google.api.field_behavior) = OUTPUT_ONLY]; // Output only. The time the conversation was finished. - google.protobuf.Timestamp end_time = 6 [(google.api.field_behavior) = OUTPUT_ONLY]; + google.protobuf.Timestamp end_time = 6 + [(google.api.field_behavior) = OUTPUT_ONLY]; } // Represents a phone number for telephony integration. It allows for connecting @@ -268,73 +245,8 @@ message ConversationPhoneNumber { string phone_number = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; } -// Represents a call matcher that describes criteria for matching incoming SIP -// calls to a conversation. When Dialogflow get a SIP call from a third-party -// carrier, Dialogflow matches the call to an existing conversation by either: -// -// * Extracting the conversation id from the -// [Call-Info header](https://tools.ietf.org/html/rfc3261#section-20.9), e.g. -// `Call-Info: -// -// ;purpose=Goog-ContactCenter-Conversation`. -// * Or, if that doesn't work, matching incoming [SIP -// headers](https://tools.ietf.org/html/rfc3261#section-7.3) -// against any [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] for the conversation. -// -// If an incoming SIP call without valid `Call-Info` header matches to zero or -// multiple conversations with `CallMatcher`, we reject it. -// -// A call matcher contains equality conditions for SIP headers that all have -// to be fulfilled in order for a SIP call to match. -// -// The matched SIP headers consist of well-known headers (`To`, `From`, -// `Call-ID`) and custom headers. A [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] is only valid if it -// specifies: -// -// * At least 1 custom header, -// * or at least 2 well-known headers. -message CallMatcher { - option (google.api.resource) = { - type: "dialogflow.googleapis.com/CallMatcher" - pattern: "projects/{project}/conversations/{conversation}/callMatchers/{call_matcher}" - pattern: "projects/{project}/locations/{location}/conversations/{conversation}/callMatchers/{call_matcher}" - }; - - // Custom SIP headers. See the [description of headers in - // the RFC](https://tools.ietf.org/html/rfc3261#section-7.3). - message CustomHeaders { - // Cisco's proprietary `Cisco-Guid` header. - string cisco_guid = 1; - } - - // Output only. The unique identifier of this call matcher. - // Format: `projects//locations//conversations//callMatchers/`. - string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // Value of the [`To` - // header](https://tools.ietf.org/html/rfc3261#section-8.1.1.2) to match. If - // empty or unspecified, we don't match to the - // [`To` header](https://tools.ietf.org/html/rfc3261#section-8.1.1.2). - string to_header = 2; - - // Value of the [`From` - // header](https://tools.ietf.org/html/rfc3261#section-8.1.1.3) to match. If - // empty or unspecified, we don't match to the - // [`From` header](https://tools.ietf.org/html/rfc3261#section-8.1.1.3). - string from_header = 3; - - // Value of the [`Call-ID` - // header](https://tools.ietf.org/html/rfc3261#section-8.1.1.4) to match. If - // empty or unspecified, we don't match to the - // [`Call-ID` header](https://tools.ietf.org/html/rfc3261#section-8.1.1.4). - string call_id_header = 4; - - // Custom SIP headers that must match. - CustomHeaders custom_headers = 5; -} - -// The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. +// The request message for +// [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. message CreateConversationRequest { // Required. Resource identifier of the project creating the conversation. // Format: `projects//locations/`. @@ -348,8 +260,8 @@ message CreateConversationRequest { // Required. The conversation to create. Conversation conversation = 2 [(google.api.field_behavior) = REQUIRED]; - // Optional. Identifier of the conversation. Generally it's auto generated by Google. - // Only set it if you cannot wait for the response to return a + // Optional. Identifier of the conversation. Generally it's auto generated by + // Google. Only set it if you cannot wait for the response to return a // auto-generated one to you. // // The conversation ID must be compliant with the regression fomula @@ -361,7 +273,8 @@ message CreateConversationRequest { string conversation_id = 3 [(google.api.field_behavior) = OPTIONAL]; } -// The request message for [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. +// The request message for +// [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. message ListConversationsRequest { // Required. The project from which to list all conversation. // Format: `projects//locations/`. @@ -399,7 +312,8 @@ message ListConversationsRequest { string filter = 4; } -// The response message for [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. +// The response message for +// [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. message ListConversationsResponse { // The list of conversations. There will be a maximum number of items // returned based on the page_size field in the request. @@ -410,7 +324,8 @@ message ListConversationsResponse { string next_page_token = 2; } -// The request message for [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. +// The request message for +// [Conversations.GetConversation][google.cloud.dialogflow.v2beta1.Conversations.GetConversation]. message GetConversationRequest { // Required. The name of the conversation. Format: // `projects//locations//conversations//locations//locations//conversations/`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "dialogflow.googleapis.com/CallMatcher" - } - ]; - - // Required. The call matcher to create. - CallMatcher call_matcher = 2; -} - -// The request message for [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. -message ListCallMatchersRequest { - // Required. The conversation to list all call matchers from. - // Format: `projects//locations//conversations/`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "dialogflow.googleapis.com/CallMatcher" - } - ]; - - // Optional. The maximum number of items to return in a single page. By - // default 100 and at most 1000. - int32 page_size = 2; - - // Optional. The next_page_token value returned from a previous list request. - string page_token = 3; -} - -// The response message for [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. -message ListCallMatchersResponse { - // The list of call matchers. There is a maximum number of items - // returned based on the page_size field in the request. - repeated CallMatcher call_matchers = 1; - - // Token to retrieve the next page of results or empty if there are no - // more results in the list. - string next_page_token = 2; -} - -// The request message for [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.DeleteCallMatcher]. -message DeleteCallMatcherRequest { - // Required. The unique identifier of the [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] to delete. - // Format: `projects//locations//conversations//callMatchers/`. - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/CallMatcher" - } - ]; -} - // The request message to create one Message. Currently it is only used in // BatchCreateMessagesRequest. message CreateMessageRequest { @@ -510,7 +366,8 @@ message CreateMessageRequest { ]; // Required. The message to create. - // [Message.participant][google.cloud.dialogflow.v2beta1.Message.participant] is required. + // [Message.participant][google.cloud.dialogflow.v2beta1.Message.participant] + // is required. Message message = 2 [(google.api.field_behavior) = REQUIRED]; } @@ -528,8 +385,10 @@ message BatchCreateMessagesRequest { // Required. A maximum of 1000 Messages can be created in a batch. // [CreateMessageRequest.message.send_time][] is required. All created - // messages will have identical [Message.create_time][google.cloud.dialogflow.v2beta1.Message.create_time]. - repeated CreateMessageRequest requests = 2 [(google.api.field_behavior) = REQUIRED]; + // messages will have identical + // [Message.create_time][google.cloud.dialogflow.v2beta1.Message.create_time]. + repeated CreateMessageRequest requests = 2 + [(google.api.field_behavior) = REQUIRED]; } // The request message for [Conversations.BatchCreateMessagesResponse][]. @@ -538,7 +397,8 @@ message BatchCreateMessagesResponse { repeated Message messages = 1; } -// The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. +// The request message for +// [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. message ListMessagesRequest { // Required. The name of the conversation to list messages for. // Format: `projects//locations//conversationModels/`. string model = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/ConversationModel" - } + (google.api.field_behavior) = REQUIRED ]; } diff --git a/google/cloud/dialogflow_v2beta1/proto/participant.proto b/google/cloud/dialogflow_v2beta1/proto/participant.proto index afe0c9faf..731b98d9b 100644 --- a/google/cloud/dialogflow_v2beta1/proto/participant.proto +++ b/google/cloud/dialogflow_v2beta1/proto/participant.proto @@ -108,28 +108,9 @@ service Participants { } }; option (google.api.method_signature) = "participant,text_input"; - option (google.api.method_signature) = "participant,audio_input"; option (google.api.method_signature) = "participant,event_input"; } - // Adds a text (e.g., chat) or audio (e.g., phone recording) message from a - // participant into the conversation. - // Note: This method is only available through the gRPC API (not REST). - // - // The top-level message sent to the client by the server is - // `StreamingAnalyzeContentResponse`. Multiple response messages can be - // returned in order. The first one or more messages contain the - // `recognition_result` field. Each result represents a more complete - // transcript of what the user said. The next message contains the - // `reply_text` field, and potentially the `reply_audio` and/or the - // `automated_agent_reply` fields. - // - // Note: Always use agent versions for production traffic - // sent to virtual agents. See [Versions and - // environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - rpc StreamingAnalyzeContent(stream StreamingAnalyzeContentRequest) returns (stream StreamingAnalyzeContentResponse) { - } - // Gets suggested articles for a participant based on specific historical // messages. // @@ -187,7 +168,7 @@ service Participants { // This method should be used by human agent client software to fetch auto // generated suggestions in real-time, while the conversation with an end user // is in progress. The functionality is implemented in terms of the - // [list pagination](/apis/design/design_patterns#list_pagination) + // [list pagination](https://cloud.google.com/apis/design/design_patterns#list_pagination) // design pattern. The client app should use the `next_page_token` field // to fetch the next batch of suggestions. `suggestions` are sorted by // `create_time` in descending order. @@ -415,17 +396,6 @@ message InputAudio { bytes audio = 2; } -// Represents the natural language speech audio to be processed. -message AudioInput { - // Required. Instructs the speech recognizer how to process the speech audio. - InputAudioConfig config = 1; - - // Required. The natural language speech audio to be processed. - // A single request can contain up to 1 minute of speech audio data. - // The transcribed text cannot contain more than 256 bytes. - bytes audio = 2; -} - // Represents the natural language speech audio to be played to the end user. message OutputAudio { // Required. Instructs the speech synthesizer how to generate the speech @@ -504,18 +474,9 @@ message AnalyzeContentRequest { // Required. The input content. oneof input { - // The natural language text to be processed. - InputText text = 3 [deprecated = true]; - - // The natural language speech audio to be processed. - InputAudio audio = 4 [deprecated = true]; - // The natural language text to be processed. TextInput text_input = 6; - // The natural language speech audio to be processed. - AudioInput audio_input = 7; - // An input event to send to Dialogflow. EventInput event_input = 8; } @@ -601,172 +562,6 @@ message AnalyzeContentResponse { DtmfParameters dtmf_parameters = 9; } -// Defines the language used in the input text. -message InputTextConfig { - // Required. The language of this conversational query. See [Language - // Support](https://cloud.google.com/dialogflow/docs/reference/language) - // for a list of the currently supported language codes. - string language_code = 1; -} - -// The top-level message sent by the client to the -// [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] method. -// -// Multiple request messages should be sent in order: -// -// 1. The first message must contain -// [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], -// [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] and optionally -// [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. If you want -// to receive an audio response, it should also contain -// [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. -// The message must not contain -// [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. -// -// 2. If [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] in the first message -// was set to [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], -// all subsequent messages must contain -// [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] to continue -// with Speech recognition. -// If you decide to rather analyze text input after you already started -// Speech recognition, please send a message with -// [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. -// -// However, note that: -// -// * Dialogflow will bill you for the audio so far. -// * Dialogflow discards all Speech recognition results in favor of the -// text input. -// -// 3. If [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] in the first message was set -// to [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], then the second message -// must contain only [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. -// Moreover, you must not send more than two messages. -// -// After you sent all input, you must half-close or abort the request stream. -message StreamingAnalyzeContentRequest { - // Required. The name of the participant this text comes from. - // Format: `projects//locations//conversations//participants/`. - string participant = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "dialogflow.googleapis.com/Participant" - } - ]; - - // Required. The input config. - oneof config { - // Instructs the speech recognizer how to process the speech audio. - InputAudioConfig audio_config = 2; - - // The natural language text to be processed. - InputTextConfig text_config = 3; - } - - // Speech synthesis configuration. - // The speech synthesis settings for a virtual agent that may be configured - // for the associated conversation profile are not used when calling - // StreamingAnalyzeContent. If this configuration is not supplied, speech - // synthesis is disabled. - OutputAudioConfig reply_audio_config = 4; - - // Required. The input. - oneof input { - // The input audio content to be recognized. Must be sent if `audio_config` - // is set in the first message. The complete audio over all streaming - // messages must not exceed 1 minute. - bytes input_audio = 5; - - // The UTF-8 encoded natural language text to be processed. Must be sent if - // `text_config` is set in the first message. Text length must not exceed - // 256 bytes. The `input_text` field can be only sent once. - string input_text = 6; - - // The DTMF digits used to invoke intent and fill in parameter value. - // - // This input is ignored if the previous response indicated that DTMF input - // is not accepted. - TelephonyDtmfEvents input_dtmf = 9; - } - - // Parameters for a Dialogflow virtual-agent query. - QueryParameters query_params = 7; - - // Enable full bidirectional streaming. You can keep streaming the audio until - // timeout, and there's no need to half close the stream to get the response. - // - // Restrictions: - // - // - Timeout: 3 mins. - // - Audio Encoding: only supports [AudioEncoding.AUDIO_ENCODING_LINEAR_16][google.cloud.dialogflow.v2beta1.AudioEncoding.AUDIO_ENCODING_LINEAR_16] - // and [AudioEncoding.AUDIO_ENCODING_MULAW][google.cloud.dialogflow.v2beta1.AudioEncoding.AUDIO_ENCODING_MULAW] - // - Lifecycle: conversation should be in `Assist Stage`, go to - // [Conversation.CreateConversation][] for more information. - // - // InvalidArgument Error will be returned if the one of restriction checks - // failed. - // - // You can find more details in - // https://cloud.google.com/dialogflow/priv/docs/agent-assist/analyze-content-streaming - bool enable_extended_streaming = 11; -} - -// The top-level message returned from the `StreamingAnalyzeContent` method. -// -// Multiple response messages can be returned in order: -// -// 1. If the input was set to streaming audio, the first one or more messages -// contain `recognition_result`. Each `recognition_result` represents a more -// complete transcript of what the user said. The last `recognition_result` -// has `is_final` set to `true`. -// -// 2. The next message contains `reply_text` and optionally `reply_audio` -// returned by an agent. This message may also contain -// `automated_agent_reply`. -message StreamingAnalyzeContentResponse { - // The result of speech recognition. - StreamingRecognitionResult recognition_result = 1; - - // Optional. The output text content. - // This field is set if an automated agent responded with a text for the user. - string reply_text = 2; - - // Optional. The audio data bytes encoded as specified in the request. - // This field is set if: - // - // - The `reply_audio_config` field is specified in the request. - // - The automated agent, which this output comes from, responded with audio. - // In such case, the `reply_audio.config` field contains settings used to - // synthesize the speech. - // - // In some scenarios, multiple output audio fields may be present in the - // response structure. In these cases, only the top-most-level audio output - // has content. - OutputAudio reply_audio = 3; - - // Optional. Only set if a Dialogflow automated agent has responded. - // Note that: [AutomatedAgentReply.detect_intent_response.output_audio][] - // and [AutomatedAgentReply.detect_intent_response.output_audio_config][] - // are always empty, use [reply_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentResponse.reply_audio] instead. - AutomatedAgentReply automated_agent_reply = 4; - - // Output only. Message analyzed by CCAI. - Message message = 6; - - // The suggestions for most recent human agent. The order is the same as - // [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of - // [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.human_agent_suggestion_config]. - repeated SuggestionResult human_agent_suggestion_results = 7; - - // The suggestions for end user. The order is the same as - // [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] of - // [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.end_user_suggestion_config]. - repeated SuggestionResult end_user_suggestion_results = 8; - - // Indicates the parameters of DTMF. - DtmfParameters dtmf_parameters = 10; -} // Represents a part of a message possibly annotated with an entity. The part // can be an entity or purely a part of the message between two entities or diff --git a/google/cloud/dialogflow_v2beta1/proto/session.proto b/google/cloud/dialogflow_v2beta1/proto/session.proto index ab5e04523..bd53acafe 100644 --- a/google/cloud/dialogflow_v2beta1/proto/session.proto +++ b/google/cloud/dialogflow_v2beta1/proto/session.proto @@ -276,6 +276,9 @@ message QueryInput { // The event to be processed. EventInput event = 3; + + // The DTMF digits used to invoke intent and fill in parameter value. + TelephonyDtmfEvents dtmf = 4; } } diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py index f8f8d44e3..7e10d2019 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py @@ -77,10 +77,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -88,6 +88,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -97,20 +100,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py index 99193b309..675d3ac95 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py @@ -112,7 +112,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -120,70 +123,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -191,18 +174,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -216,7 +189,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py index 2ddc8ca85..ad50f2638 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py @@ -67,7 +67,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -145,10 +145,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -157,7 +157,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -165,70 +168,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -236,18 +219,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py b/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py index dfeb91746..5e3908a60 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py @@ -227,11 +227,12 @@ async def get_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. + 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe - is wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe is + wrong. """ # Create or coerce a protobuf request object. @@ -292,7 +293,7 @@ async def list_answer_records( Returns: google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsAsyncPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -407,11 +408,12 @@ async def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. + 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe - is wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe is + wrong. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/client.py b/google/cloud/dialogflow_v2beta1/services/answer_records/client.py index 08e56aa52..a0cceb54b 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/client.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/client.py @@ -396,11 +396,12 @@ def get_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. + 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe - is wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe is + wrong. """ # Create or coerce a protobuf request object. @@ -462,7 +463,7 @@ def list_answer_records( Returns: google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -578,11 +579,12 @@ def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. + 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe - is wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe is + wrong. """ # Create or coerce a protobuf request object. diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py index 408c4495d..1fb664a96 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py index 7a93b52ff..19901a8f3 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py @@ -108,7 +108,9 @@ def __init__( 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) @@ -116,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -187,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -211,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py index 62c4531f8..a0e18f180 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py @@ -63,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -141,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -153,7 +153,9 @@ def __init__( 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) @@ -161,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -232,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py index 664f3e3fc..1d3b4783b 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py @@ -74,10 +74,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,6 +85,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -94,20 +97,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py index 020b3d9ec..ae75375c9 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py @@ -109,7 +109,9 @@ def __init__( 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) @@ -117,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,17 +170,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -212,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py index f06a162f5..3e2d8fdfb 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py @@ -64,7 +64,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -142,10 +142,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +215,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py index 4bc3e09fd..a7f357435 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py index 3d5442260..80cd9e78f 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py @@ -111,7 +111,9 @@ def __init__( 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) @@ -119,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,17 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py index 8f2997c38..72244a461 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py b/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py index ad27edf78..cf4fb1475 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py @@ -49,8 +49,6 @@ class ConversationsAsyncClient: DEFAULT_ENDPOINT = ConversationsClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = ConversationsClient.DEFAULT_MTLS_ENDPOINT - call_matcher_path = staticmethod(ConversationsClient.call_matcher_path) - parse_call_matcher_path = staticmethod(ConversationsClient.parse_call_matcher_path) conversation_path = staticmethod(ConversationsClient.conversation_path) parse_conversation_path = staticmethod(ConversationsClient.parse_conversation_path) conversation_profile_path = staticmethod( @@ -325,7 +323,7 @@ async def list_conversations( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsAsyncPager: The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. Iterating over this object will yield results and resolve additional pages automatically. @@ -534,272 +532,6 @@ async def complete_conversation( # Done; return the response. return response - async def create_call_matcher( - self, - request: conversation.CreateCallMatcherRequest = None, - *, - parent: str = None, - call_matcher: conversation.CallMatcher = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.CallMatcher: - r"""Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.CreateCallMatcherRequest`): - The request object. The request message for - [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.CreateCallMatcher]. - parent (:class:`str`): - Required. Resource identifier of the conversation adding - the call matcher. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - call_matcher (:class:`google.cloud.dialogflow_v2beta1.types.CallMatcher`): - Required. The call matcher to create. - This corresponds to the ``call_matcher`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.CallMatcher: - Represents a call matcher that describes criteria for matching incoming SIP - calls to a conversation. When Dialogflow get a SIP - call from a third-party carrier, Dialogflow matches - the call to an existing conversation by either: - - - Extracting the conversation id from the [Call-Info - header](\ https://tools.ietf.org/html/rfc3261#section-20.9), - e.g. Call-Info: - - ;purpose=Goog-ContactCenter-Conversation. - - \* Or, if that doesn't work, matching incoming [SIP - headers](\ https://tools.ietf.org/html/rfc3261#section-7.3) - against any - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - for the conversation. - - If an incoming SIP call without valid Call-Info - header matches to zero or multiple conversations with - CallMatcher, we reject it. - - A call matcher contains equality conditions for SIP - headers that all have to be fulfilled in order for a - SIP call to match. - - The matched SIP headers consist of well-known headers - (To, From, Call-ID) and custom headers. A - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - is only valid if it specifies: - - - At least 1 custom header, - - or at least 2 well-known headers. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, call_matcher]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = conversation.CreateCallMatcherRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if call_matcher is not None: - request.call_matcher = call_matcher - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_call_matcher, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_call_matchers( - self, - request: conversation.ListCallMatchersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCallMatchersAsyncPager: - r"""Returns the list of all call matchers in the - specified conversation. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.ListCallMatchersRequest`): - The request object. The request message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. - parent (:class:`str`): - Required. The conversation to list all call matchers - from. Format: - ``projects//locations//conversations/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListCallMatchersAsyncPager: - The response message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = conversation.ListCallMatchersRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_call_matchers, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # 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.ListCallMatchersAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_call_matcher( - self, - request: conversation.DeleteCallMatcherRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Requests deletion of a call matcher. - - Args: - request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteCallMatcherRequest`): - The request object. The request message for - [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.DeleteCallMatcher]. - name (:class:`str`): - Required. The unique identifier of the - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - to delete. Format: - ``projects//locations//conversations//callMatchers/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = conversation.DeleteCallMatcherRequest(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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_call_matcher, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - await rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - async def batch_create_messages( self, request: conversation.BatchCreateMessagesRequest = None, @@ -913,7 +645,7 @@ async def list_messages( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesAsyncPager: The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. Iterating over this object will yield results and resolve additional pages automatically. diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/client.py b/google/cloud/dialogflow_v2beta1/services/conversations/client.py index 1855fe92d..5dee0325f 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/client.py @@ -158,22 +158,6 @@ def transport(self) -> ConversationsTransport: """ return self._transport - @staticmethod - def call_matcher_path(project: str, conversation: str, call_matcher: str,) -> str: - """Return a fully-qualified call_matcher string.""" - return "projects/{project}/conversations/{conversation}/callMatchers/{call_matcher}".format( - project=project, conversation=conversation, call_matcher=call_matcher, - ) - - @staticmethod - def parse_call_matcher_path(path: str) -> Dict[str, str]: - """Parse a call_matcher path into its component segments.""" - m = re.match( - r"^projects/(?P.+?)/conversations/(?P.+?)/callMatchers/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - @staticmethod def conversation_path(project: str, conversation: str,) -> str: """Return a fully-qualified conversation string.""" @@ -535,7 +519,7 @@ def list_conversations( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsPager: The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. Iterating over this object will yield results and resolve additional pages automatically. @@ -747,275 +731,6 @@ def complete_conversation( # Done; return the response. return response - def create_call_matcher( - self, - request: conversation.CreateCallMatcherRequest = None, - *, - parent: str = None, - call_matcher: conversation.CallMatcher = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.CallMatcher: - r"""Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Args: - request (google.cloud.dialogflow_v2beta1.types.CreateCallMatcherRequest): - The request object. The request message for - [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.CreateCallMatcher]. - parent (str): - Required. Resource identifier of the conversation adding - the call matcher. Format: - ``projects//locations//conversations/``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - call_matcher (google.cloud.dialogflow_v2beta1.types.CallMatcher): - Required. The call matcher to create. - This corresponds to the ``call_matcher`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.types.CallMatcher: - Represents a call matcher that describes criteria for matching incoming SIP - calls to a conversation. When Dialogflow get a SIP - call from a third-party carrier, Dialogflow matches - the call to an existing conversation by either: - - - Extracting the conversation id from the [Call-Info - header](\ https://tools.ietf.org/html/rfc3261#section-20.9), - e.g. Call-Info: - - ;purpose=Goog-ContactCenter-Conversation. - - \* Or, if that doesn't work, matching incoming [SIP - headers](\ https://tools.ietf.org/html/rfc3261#section-7.3) - against any - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - for the conversation. - - If an incoming SIP call without valid Call-Info - header matches to zero or multiple conversations with - CallMatcher, we reject it. - - A call matcher contains equality conditions for SIP - headers that all have to be fulfilled in order for a - SIP call to match. - - The matched SIP headers consist of well-known headers - (To, From, Call-ID) and custom headers. A - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - is only valid if it specifies: - - - At least 1 custom header, - - or at least 2 well-known headers. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, call_matcher]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a conversation.CreateCallMatcherRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation.CreateCallMatcherRequest): - request = conversation.CreateCallMatcherRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if call_matcher is not None: - request.call_matcher = call_matcher - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_call_matcher] - - # 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),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_call_matchers( - self, - request: conversation.ListCallMatchersRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListCallMatchersPager: - r"""Returns the list of all call matchers in the - specified conversation. - - Args: - request (google.cloud.dialogflow_v2beta1.types.ListCallMatchersRequest): - The request object. The request message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. - parent (str): - Required. The conversation to list all call matchers - from. Format: - ``projects//locations//conversations/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListCallMatchersPager: - The response message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a conversation.ListCallMatchersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation.ListCallMatchersRequest): - request = conversation.ListCallMatchersRequest(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_call_matchers] - - # 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),)), - ) - - # 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.ListCallMatchersPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_call_matcher( - self, - request: conversation.DeleteCallMatcherRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Requests deletion of a call matcher. - - Args: - request (google.cloud.dialogflow_v2beta1.types.DeleteCallMatcherRequest): - The request object. The request message for - [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.DeleteCallMatcher]. - name (str): - Required. The unique identifier of the - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - to delete. Format: - ``projects//locations//conversations//callMatchers/``. - - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a conversation.DeleteCallMatcherRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversation.DeleteCallMatcherRequest): - request = conversation.DeleteCallMatcherRequest(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_call_matcher] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - def batch_create_messages( self, request: conversation.BatchCreateMessagesRequest = None, @@ -1130,7 +845,7 @@ def list_messages( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesPager: The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. Iterating over this object will yield results and resolve additional pages automatically. diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py b/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py index eb97134b9..f9a2ca203 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py @@ -158,134 +158,6 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) -class ListCallMatchersPager: - """A pager for iterating through ``list_call_matchers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListCallMatchersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``call_matchers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCallMatchers`` requests and continue to iterate - through the ``call_matchers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListCallMatchersResponse` - 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[..., conversation.ListCallMatchersResponse], - request: conversation.ListCallMatchersRequest, - response: conversation.ListCallMatchersResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListCallMatchersRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListCallMatchersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversation.ListCallMatchersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[conversation.ListCallMatchersResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[conversation.CallMatcher]: - for page in self.pages: - yield from page.call_matchers - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListCallMatchersAsyncPager: - """A pager for iterating through ``list_call_matchers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.dialogflow_v2beta1.types.ListCallMatchersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``call_matchers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCallMatchers`` requests and continue to iterate - through the ``call_matchers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListCallMatchersResponse` - 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[conversation.ListCallMatchersResponse]], - request: conversation.ListCallMatchersRequest, - response: conversation.ListCallMatchersResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.dialogflow_v2beta1.types.ListCallMatchersRequest): - The initial request object. - response (google.cloud.dialogflow_v2beta1.types.ListCallMatchersResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversation.ListCallMatchersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[conversation.ListCallMatchersResponse]: - 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, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[conversation.CallMatcher]: - async def async_generator(): - async for page in self.pages: - for response in page.call_matchers: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - class ListMessagesPager: """A pager for iterating through ``list_messages`` requests. diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py index 16abd668a..ecc38991b 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py @@ -27,7 +27,6 @@ from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.protobuf import empty_pb2 as empty # type: ignore try: @@ -74,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -94,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -125,15 +124,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), - self.create_call_matcher: gapic_v1.method.wrap_method( - self.create_call_matcher, default_timeout=None, client_info=client_info, - ), - self.list_call_matchers: gapic_v1.method.wrap_method( - self.list_call_matchers, default_timeout=None, client_info=client_info, - ), - self.delete_call_matcher: gapic_v1.method.wrap_method( - self.delete_call_matcher, default_timeout=None, client_info=client_info, - ), self.batch_create_messages: gapic_v1.method.wrap_method( self.batch_create_messages, default_timeout=None, @@ -190,38 +180,6 @@ def complete_conversation( ]: raise NotImplementedError() - @property - def create_call_matcher( - self, - ) -> typing.Callable[ - [conversation.CreateCallMatcherRequest], - typing.Union[ - conversation.CallMatcher, typing.Awaitable[conversation.CallMatcher] - ], - ]: - raise NotImplementedError() - - @property - def list_call_matchers( - self, - ) -> typing.Callable[ - [conversation.ListCallMatchersRequest], - typing.Union[ - conversation.ListCallMatchersResponse, - typing.Awaitable[conversation.ListCallMatchersResponse], - ], - ]: - raise NotImplementedError() - - @property - def delete_call_matcher( - self, - ) -> typing.Callable[ - [conversation.DeleteCallMatcherRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], - ]: - raise NotImplementedError() - @property def batch_create_messages( self, diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py index 7e84c5300..c0f5c981a 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py @@ -28,7 +28,6 @@ from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.protobuf import empty_pb2 as empty # type: ignore from .base import ConversationsTransport, DEFAULT_CLIENT_INFO @@ -109,7 +108,9 @@ def __init__( 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) @@ -117,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -212,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -384,89 +356,6 @@ def complete_conversation( ) return self._stubs["complete_conversation"] - @property - def create_call_matcher( - self, - ) -> Callable[[conversation.CreateCallMatcherRequest], conversation.CallMatcher]: - r"""Return a callable for the create call matcher method over gRPC. - - Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Returns: - Callable[[~.CreateCallMatcherRequest], - ~.CallMatcher]: - 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_call_matcher" not in self._stubs: - self._stubs["create_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2beta1.Conversations/CreateCallMatcher", - request_serializer=conversation.CreateCallMatcherRequest.serialize, - response_deserializer=conversation.CallMatcher.deserialize, - ) - return self._stubs["create_call_matcher"] - - @property - def list_call_matchers( - self, - ) -> Callable[ - [conversation.ListCallMatchersRequest], conversation.ListCallMatchersResponse - ]: - r"""Return a callable for the list call matchers method over gRPC. - - Returns the list of all call matchers in the - specified conversation. - - Returns: - Callable[[~.ListCallMatchersRequest], - ~.ListCallMatchersResponse]: - 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_call_matchers" not in self._stubs: - self._stubs["list_call_matchers"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2beta1.Conversations/ListCallMatchers", - request_serializer=conversation.ListCallMatchersRequest.serialize, - response_deserializer=conversation.ListCallMatchersResponse.deserialize, - ) - return self._stubs["list_call_matchers"] - - @property - def delete_call_matcher( - self, - ) -> Callable[[conversation.DeleteCallMatcherRequest], empty.Empty]: - r"""Return a callable for the delete call matcher method over gRPC. - - Requests deletion of a call matcher. - - Returns: - Callable[[~.DeleteCallMatcherRequest], - ~.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_call_matcher" not in self._stubs: - self._stubs["delete_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2beta1.Conversations/DeleteCallMatcher", - request_serializer=conversation.DeleteCallMatcherRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_call_matcher"] - @property def batch_create_messages( self, diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py index 7bdb25dca..a00f0288d 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py @@ -29,7 +29,6 @@ from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation -from google.protobuf import empty_pb2 as empty # type: ignore from .base import ConversationsTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationsGrpcTransport @@ -64,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -142,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -154,7 +153,9 @@ def __init__( 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) @@ -162,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -392,92 +364,6 @@ def complete_conversation( ) return self._stubs["complete_conversation"] - @property - def create_call_matcher( - self, - ) -> Callable[ - [conversation.CreateCallMatcherRequest], Awaitable[conversation.CallMatcher] - ]: - r"""Return a callable for the create call matcher method over gRPC. - - Creates a call matcher that links incoming SIP calls - to the specified conversation if they fulfill specified - criteria. - - Returns: - Callable[[~.CreateCallMatcherRequest], - Awaitable[~.CallMatcher]]: - 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_call_matcher" not in self._stubs: - self._stubs["create_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2beta1.Conversations/CreateCallMatcher", - request_serializer=conversation.CreateCallMatcherRequest.serialize, - response_deserializer=conversation.CallMatcher.deserialize, - ) - return self._stubs["create_call_matcher"] - - @property - def list_call_matchers( - self, - ) -> Callable[ - [conversation.ListCallMatchersRequest], - Awaitable[conversation.ListCallMatchersResponse], - ]: - r"""Return a callable for the list call matchers method over gRPC. - - Returns the list of all call matchers in the - specified conversation. - - Returns: - Callable[[~.ListCallMatchersRequest], - Awaitable[~.ListCallMatchersResponse]]: - 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_call_matchers" not in self._stubs: - self._stubs["list_call_matchers"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2beta1.Conversations/ListCallMatchers", - request_serializer=conversation.ListCallMatchersRequest.serialize, - response_deserializer=conversation.ListCallMatchersResponse.deserialize, - ) - return self._stubs["list_call_matchers"] - - @property - def delete_call_matcher( - self, - ) -> Callable[[conversation.DeleteCallMatcherRequest], Awaitable[empty.Empty]]: - r"""Return a callable for the delete call matcher method over gRPC. - - Requests deletion of a call matcher. - - Returns: - Callable[[~.DeleteCallMatcherRequest], - 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_call_matcher" not in self._stubs: - self._stubs["delete_call_matcher"] = self.grpc_channel.unary_unary( - "/google.cloud.dialogflow.v2beta1.Conversations/DeleteCallMatcher", - request_serializer=conversation.DeleteCallMatcherRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_call_matcher"] - @property def batch_create_messages( self, diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py index 8f59da111..352d60dce 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py @@ -75,10 +75,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -86,6 +86,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -95,20 +98,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py index bee3ec46e..11c7488ee 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py @@ -110,7 +110,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -118,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,18 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py index 6e04daec1..112d72a50 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py @@ -65,7 +65,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -143,10 +143,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -155,7 +155,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -163,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py index c04f42d99..3b3c283cd 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py index eb180c61f..3cd835d14 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py @@ -111,7 +111,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,18 +173,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -215,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py index 53985db1c..c4f4439fd 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +218,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py index 1a452c274..d48fa645e 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py @@ -72,10 +72,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -83,6 +83,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -92,20 +95,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py index de5505597..6fb0cd7e2 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py @@ -107,7 +107,9 @@ def __init__( 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) @@ -115,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -186,17 +168,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -210,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py index bce9fca5b..52b0b3ba7 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py @@ -62,7 +62,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -140,10 +140,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -152,7 +152,9 @@ def __init__( 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) @@ -160,70 +162,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -231,17 +213,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py index 5c57ffe4a..b49fd88d1 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py index c9d7893e6..792e437cc 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py @@ -111,7 +111,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +122,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,18 +173,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -215,7 +188,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py index e24b339d6..f8cfe4546 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +218,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py index e013e1e1e..900d39a5f 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py @@ -74,10 +74,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,6 +85,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -94,20 +97,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py index 88d8173f4..563d0d737 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py @@ -109,7 +109,9 @@ def __init__( 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) @@ -117,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,17 +170,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -212,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py index 19f40dc07..589b6cf50 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py @@ -64,7 +64,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -142,10 +142,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +215,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py index a9ede9faa..ac4e64e35 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py @@ -18,16 +18,7 @@ from collections import OrderedDict import functools import re -from typing import ( - Dict, - AsyncIterable, - Awaitable, - AsyncIterator, - Sequence, - Tuple, - Type, - Union, -) +from typing import Dict, Sequence, Tuple, Type, Union import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore @@ -519,7 +510,6 @@ async def analyze_content( *, participant: str = None, text_input: session.TextInput = None, - audio_input: gcd_participant.AudioInput = None, event_input: session.EventInput = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -551,13 +541,6 @@ async def analyze_content( This corresponds to the ``text_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - audio_input (:class:`google.cloud.dialogflow_v2beta1.types.AudioInput`): - The natural language speech audio to - be processed. - - This corresponds to the ``audio_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. event_input (:class:`google.cloud.dialogflow_v2beta1.types.EventInput`): An input event to send to Dialogflow. This corresponds to the ``event_input`` field @@ -579,7 +562,7 @@ async def analyze_content( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, audio_input, event_input]) + has_flattened_params = any([participant, text_input, event_input]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -595,8 +578,6 @@ async def analyze_content( request.participant = participant if text_input is not None: request.text_input = text_input - if audio_input is not None: - request.audio_input = audio_input if event_input is not None: request.event_input = event_input @@ -609,6 +590,7 @@ async def analyze_content( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, @@ -628,112 +610,6 @@ async def analyze_content( # Done; return the response. return response - def streaming_analyze_content( - self, - requests: AsyncIterator[participant.StreamingAnalyzeContentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Awaitable[AsyncIterable[participant.StreamingAnalyzeContentResponse]]: - r"""Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Args: - requests (AsyncIterator[`google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest`]): - The request object AsyncIterator. The top-level message sent by the - client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. - If you decide to rather analyze text input after you - already started Speech recognition, please send a - message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - However, note that: - - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort - the request stream. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - AsyncIterable[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. The next message contains reply_text and - optionally reply_audio returned by an agent. This - message may also contain automated_agent_reply. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.streaming_analyze_content, - default_timeout=220.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Send the request. - response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - async def suggest_articles( self, request: participant.SuggestArticlesRequest = None, @@ -985,7 +861,7 @@ async def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/participants/client.py b/google/cloud/dialogflow_v2beta1/services/participants/client.py index 583b5f7c3..ae9ace66c 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/client.py @@ -19,17 +19,7 @@ from distutils import util import os import re -from typing import ( - Callable, - Dict, - Optional, - Iterable, - Iterator, - Sequence, - Tuple, - Type, - Union, -) +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore @@ -765,7 +755,6 @@ def analyze_content( *, participant: str = None, text_input: session.TextInput = None, - audio_input: gcd_participant.AudioInput = None, event_input: session.EventInput = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -797,13 +786,6 @@ def analyze_content( This corresponds to the ``text_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - audio_input (google.cloud.dialogflow_v2beta1.types.AudioInput): - The natural language speech audio to - be processed. - - This corresponds to the ``audio_input`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. event_input (google.cloud.dialogflow_v2beta1.types.EventInput): An input event to send to Dialogflow. This corresponds to the ``event_input`` field @@ -825,7 +807,7 @@ def analyze_content( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - has_flattened_params = any([participant, text_input, audio_input, event_input]) + has_flattened_params = any([participant, text_input, event_input]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -846,8 +828,6 @@ def analyze_content( request.participant = participant if text_input is not None: request.text_input = text_input - if audio_input is not None: - request.audio_input = audio_input if event_input is not None: request.event_input = event_input @@ -869,110 +849,6 @@ def analyze_content( # Done; return the response. return response - def streaming_analyze_content( - self, - requests: Iterator[participant.StreamingAnalyzeContentRequest] = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> Iterable[participant.StreamingAnalyzeContentResponse]: - r"""Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Args: - requests (Iterator[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentRequest]): - The request object iterator. The top-level message sent by the - client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method. - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should - also contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. - If you decide to rather analyze text input after you - already started Speech recognition, please send a - message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - However, note that: - - * Dialogflow will bill you for the audio so far. - * Dialogflow discards all Speech recognition results - in favor of the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - After you sent all input, you must half-close or abort - the request stream. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - Iterable[google.cloud.dialogflow_v2beta1.types.StreamingAnalyzeContentResponse]: - The top-level message returned from the - StreamingAnalyzeContent method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first - one or more messages contain recognition_result. - Each recognition_result represents a more complete - transcript of what the user said. The last - recognition_result has is_final set to true. - 2. The next message contains reply_text and - optionally reply_audio returned by an agent. This - message may also contain automated_agent_reply. - - """ - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.streaming_analyze_content - ] - - # Send the request. - response = rpc(requests, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - def suggest_articles( self, request: participant.SuggestArticlesRequest = None, @@ -1227,7 +1103,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py index eda539300..6c63884a8 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -129,15 +129,11 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=client_info, ), - self.streaming_analyze_content: gapic_v1.method.wrap_method( - self.streaming_analyze_content, - default_timeout=220.0, - client_info=client_info, - ), self.suggest_articles: gapic_v1.method.wrap_method( self.suggest_articles, default_timeout=None, client_info=client_info, ), @@ -214,18 +210,6 @@ def analyze_content( ]: raise NotImplementedError() - @property - def streaming_analyze_content( - self, - ) -> typing.Callable[ - [participant.StreamingAnalyzeContentRequest], - typing.Union[ - participant.StreamingAnalyzeContentResponse, - typing.Awaitable[participant.StreamingAnalyzeContentResponse], - ], - ]: - raise NotImplementedError() - @property def suggest_articles( self, diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py index 959346114..04560ca1e 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py @@ -108,7 +108,9 @@ def __init__( 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) @@ -116,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -187,17 +169,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -211,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -394,49 +367,6 @@ def analyze_content( ) return self._stubs["analyze_content"] - @property - def streaming_analyze_content( - self, - ) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - participant.StreamingAnalyzeContentResponse, - ]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - ~.StreamingAnalyzeContentResponse]: - 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 "streaming_analyze_content" not in self._stubs: - self._stubs["streaming_analyze_content"] = self.grpc_channel.stream_stream( - "/google.cloud.dialogflow.v2beta1.Participants/StreamingAnalyzeContent", - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs["streaming_analyze_content"] - @property def suggest_articles( self, @@ -551,7 +481,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py index 0385717d2..ad713f7d5 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py @@ -63,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -141,10 +141,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -153,7 +153,9 @@ def __init__( 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) @@ -161,70 +163,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -232,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -404,49 +377,6 @@ def analyze_content( ) return self._stubs["analyze_content"] - @property - def streaming_analyze_content( - self, - ) -> Callable[ - [participant.StreamingAnalyzeContentRequest], - Awaitable[participant.StreamingAnalyzeContentResponse], - ]: - r"""Return a callable for the streaming analyze content method over gRPC. - - Adds a text (e.g., chat) or audio (e.g., phone recording) - message from a participant into the conversation. Note: This - method is only available through the gRPC API (not REST). - - The top-level message sent to the client by the server is - ``StreamingAnalyzeContentResponse``. Multiple response messages - can be returned in order. The first one or more messages contain - the ``recognition_result`` field. Each result represents a more - complete transcript of what the user said. The next message - contains the ``reply_text`` field, and potentially the - ``reply_audio`` and/or the ``automated_agent_reply`` fields. - - Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). - - Returns: - Callable[[~.StreamingAnalyzeContentRequest], - Awaitable[~.StreamingAnalyzeContentResponse]]: - 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 "streaming_analyze_content" not in self._stubs: - self._stubs["streaming_analyze_content"] = self.grpc_channel.stream_stream( - "/google.cloud.dialogflow.v2beta1.Participants/StreamingAnalyzeContent", - request_serializer=participant.StreamingAnalyzeContentRequest.serialize, - response_deserializer=participant.StreamingAnalyzeContentResponse.deserialize, - ) - return self._stubs["streaming_analyze_content"] - @property def suggest_articles( self, @@ -564,7 +494,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py index 574b6c1e4..e3e62fc17 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py @@ -76,10 +76,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,6 +87,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -96,20 +99,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py index 6fc05f9a9..6ef126d94 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py @@ -111,7 +111,9 @@ def __init__( 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) @@ -119,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,17 +172,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -214,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py index 840eeb67d..10e5ecdfd 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py @@ -66,7 +66,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -144,10 +144,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py index ac247692e..c62121f7d 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py @@ -295,6 +295,7 @@ async def detect_intent( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py index 847196c05..24431128f 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py @@ -73,10 +73,10 @@ def __init__( scope (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 + 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -84,6 +84,9 @@ def __init__( host += ":443" self._host = host + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: @@ -93,20 +96,17 @@ def __init__( if credentials_file is not None: credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials_file, scopes=self._scopes, quota_project_id=quota_project_id ) elif credentials is None: credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + scopes=self._scopes, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -117,6 +117,7 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + deadline=220.0, ), default_timeout=220.0, client_info=client_info, diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py index 43862fa89..c1fc1907c 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py @@ -110,7 +110,9 @@ def __init__( 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) @@ -118,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,17 +171,8 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @classmethod def create_channel( @@ -213,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py index 47502e9d5..ad283b9d5 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py @@ -65,7 +65,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -143,10 +143,10 @@ def __init__( ignored if ``channel`` 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 + 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: @@ -155,7 +155,9 @@ def __init__( 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) @@ -163,70 +165,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # Ignore credentials if a channel was passed. credentials = False - # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,17 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflow_v2beta1/types/__init__.py b/google/cloud/dialogflow_v2beta1/types/__init__.py index 924295b40..e62387547 100644 --- a/google/cloud/dialogflow_v2beta1/types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/types/__init__.py @@ -68,17 +68,12 @@ from .conversation import ( BatchCreateMessagesRequest, BatchCreateMessagesResponse, - CallMatcher, CompleteConversationRequest, Conversation, ConversationPhoneNumber, - CreateCallMatcherRequest, CreateConversationRequest, CreateMessageRequest, - DeleteCallMatcherRequest, GetConversationRequest, - ListCallMatchersRequest, - ListCallMatchersResponse, ListConversationsRequest, ListConversationsResponse, ListMessagesRequest, @@ -167,7 +162,6 @@ AnalyzeContentResponse, AnnotatedMessagePart, ArticleAnswer, - AudioInput, AutomatedAgentReply, CompileSuggestionRequest, CompileSuggestionResponse, @@ -177,7 +171,6 @@ GetParticipantRequest, InputAudio, InputText, - InputTextConfig, ListParticipantsRequest, ListParticipantsResponse, ListSuggestionsRequest, @@ -188,8 +181,6 @@ Participant, ResponseMessage, SmartReplyAnswer, - StreamingAnalyzeContentRequest, - StreamingAnalyzeContentResponse, SuggestArticlesRequest, SuggestArticlesResponse, SuggestFaqAnswersRequest, @@ -281,17 +272,12 @@ "UpdateContextRequest", "BatchCreateMessagesRequest", "BatchCreateMessagesResponse", - "CallMatcher", "CompleteConversationRequest", "Conversation", "ConversationPhoneNumber", - "CreateCallMatcherRequest", "CreateConversationRequest", "CreateMessageRequest", - "DeleteCallMatcherRequest", "GetConversationRequest", - "ListCallMatchersRequest", - "ListCallMatchersResponse", "ListConversationsRequest", "ListConversationsResponse", "ListMessagesRequest", @@ -364,7 +350,6 @@ "AnalyzeContentResponse", "AnnotatedMessagePart", "ArticleAnswer", - "AudioInput", "AutomatedAgentReply", "CompileSuggestionRequest", "CompileSuggestionResponse", @@ -374,7 +359,6 @@ "GetParticipantRequest", "InputAudio", "InputText", - "InputTextConfig", "ListParticipantsRequest", "ListParticipantsResponse", "ListSuggestionsRequest", @@ -385,8 +369,6 @@ "Participant", "ResponseMessage", "SmartReplyAnswer", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "SuggestArticlesRequest", "SuggestArticlesResponse", "SuggestFaqAnswersRequest", diff --git a/google/cloud/dialogflow_v2beta1/types/audio_config.py b/google/cloud/dialogflow_v2beta1/types/audio_config.py index 5fffbd881..fda8a8e73 100644 --- a/google/cloud/dialogflow_v2beta1/types/audio_config.py +++ b/google/cloud/dialogflow_v2beta1/types/audio_config.py @@ -90,7 +90,9 @@ class OutputAudioEncoding(proto.Enum): OUTPUT_AUDIO_ENCODING_UNSPECIFIED = 0 OUTPUT_AUDIO_ENCODING_LINEAR_16 = 1 OUTPUT_AUDIO_ENCODING_MP3 = 2 + OUTPUT_AUDIO_ENCODING_MP3_64_KBPS = 4 OUTPUT_AUDIO_ENCODING_OGG_OPUS = 3 + OUTPUT_AUDIO_ENCODING_MULAW = 5 class TelephonyDtmf(proto.Enum): diff --git a/google/cloud/dialogflow_v2beta1/types/conversation.py b/google/cloud/dialogflow_v2beta1/types/conversation.py index 4fe64ebf2..11ffff26c 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation.py @@ -27,16 +27,11 @@ manifest={ "Conversation", "ConversationPhoneNumber", - "CallMatcher", "CreateConversationRequest", "ListConversationsRequest", "ListConversationsResponse", "GetConversationRequest", "CompleteConversationRequest", - "CreateCallMatcherRequest", - "ListCallMatchersRequest", - "ListCallMatchersResponse", - "DeleteCallMatcherRequest", "CreateMessageRequest", "BatchCreateMessagesRequest", "BatchCreateMessagesResponse", @@ -140,86 +135,6 @@ class ConversationPhoneNumber(proto.Message): phone_number = proto.Field(proto.STRING, number=3) -class CallMatcher(proto.Message): - r"""Represents a call matcher that describes criteria for matching - incoming SIP calls to a conversation. When Dialogflow get a SIP call - from a third-party carrier, Dialogflow matches the call to an - existing conversation by either: - - - Extracting the conversation id from the `Call-Info - header `__, - e.g. - ``Call-Info: ;purpose=Goog-ContactCenter-Conversation``. - - Or, if that doesn't work, matching incoming `SIP - headers `__ - against any - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] for - the conversation. - - If an incoming SIP call without valid ``Call-Info`` header matches - to zero or multiple conversations with ``CallMatcher``, we reject - it. - - A call matcher contains equality conditions for SIP headers that all - have to be fulfilled in order for a SIP call to match. - - The matched SIP headers consist of well-known headers (``To``, - ``From``, ``Call-ID``) and custom headers. A - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] is only - valid if it specifies: - - - At least 1 custom header, - - or at least 2 well-known headers. - - Attributes: - name (str): - Output only. The unique identifier of this call matcher. - Format: - ``projects//locations//conversations//callMatchers/``. - to_header (str): - Value of the ```To`` - header `__ - to match. If empty or unspecified, we don't match to the - ```To`` - header `__. - from_header (str): - Value of the ```From`` - header `__ - to match. If empty or unspecified, we don't match to the - ```From`` - header `__. - call_id_header (str): - Value of the ```Call-ID`` - header `__ - to match. If empty or unspecified, we don't match to the - ```Call-ID`` - header `__. - custom_headers (google.cloud.dialogflow_v2beta1.types.CallMatcher.CustomHeaders): - Custom SIP headers that must match. - """ - - class CustomHeaders(proto.Message): - r"""Custom SIP headers. See the `description of headers in the - RFC `__. - - Attributes: - cisco_guid (str): - Cisco's proprietary ``Cisco-Guid`` header. - """ - - cisco_guid = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - to_header = proto.Field(proto.STRING, number=2) - - from_header = proto.Field(proto.STRING, number=3) - - call_id_header = proto.Field(proto.STRING, number=4) - - custom_headers = proto.Field(proto.MESSAGE, number=5, message=CustomHeaders,) - - class CreateConversationRequest(proto.Message): r"""The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2beta1.Conversations.CreateConversation]. @@ -354,86 +269,6 @@ class CompleteConversationRequest(proto.Message): name = proto.Field(proto.STRING, number=1) -class CreateCallMatcherRequest(proto.Message): - r"""The request message for - [Conversations.CreateCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.CreateCallMatcher]. - - Attributes: - parent (str): - Required. Resource identifier of the conversation adding the - call matcher. Format: - ``projects//locations//conversations/``. - call_matcher (google.cloud.dialogflow_v2beta1.types.CallMatcher): - Required. The call matcher to create. - """ - - parent = proto.Field(proto.STRING, number=1) - - call_matcher = proto.Field(proto.MESSAGE, number=2, message="CallMatcher",) - - -class ListCallMatchersRequest(proto.Message): - r"""The request message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. - - Attributes: - parent (str): - Required. The conversation to list all call matchers from. - Format: - ``projects//locations//conversations/``. - page_size (int): - Optional. The maximum number of items to - return in a single page. By default 100 and at - most 1000. - page_token (str): - Optional. The next_page_token value returned from a previous - list request. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - -class ListCallMatchersResponse(proto.Message): - r"""The response message for - [Conversations.ListCallMatchers][google.cloud.dialogflow.v2beta1.Conversations.ListCallMatchers]. - - Attributes: - call_matchers (Sequence[google.cloud.dialogflow_v2beta1.types.CallMatcher]): - The list of call matchers. There is a maximum number of - items returned based on the page_size field in the request. - next_page_token (str): - Token to retrieve the next page of results or - empty if there are no more results in the list. - """ - - @property - def raw_page(self): - return self - - call_matchers = proto.RepeatedField(proto.MESSAGE, number=1, message="CallMatcher",) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class DeleteCallMatcherRequest(proto.Message): - r"""The request message for - [Conversations.DeleteCallMatcher][google.cloud.dialogflow.v2beta1.Conversations.DeleteCallMatcher]. - - Attributes: - name (str): - Required. The unique identifier of the - [CallMatcher][google.cloud.dialogflow.v2beta1.CallMatcher] - to delete. Format: - ``projects//locations//conversations//callMatchers/``. - """ - - name = proto.Field(proto.STRING, number=1) - - class CreateMessageRequest(proto.Message): r"""The request message to create one Message. Currently it is only used in BatchCreateMessagesRequest. diff --git a/google/cloud/dialogflow_v2beta1/types/participant.py b/google/cloud/dialogflow_v2beta1/types/participant.py index d6142d689..33e507a67 100644 --- a/google/cloud/dialogflow_v2beta1/types/participant.py +++ b/google/cloud/dialogflow_v2beta1/types/participant.py @@ -18,7 +18,7 @@ import proto # type: ignore -from google.cloud.dialogflow_v2beta1.types import audio_config as gcd_audio_config +from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session from google.protobuf import field_mask_pb2 as field_mask # type: ignore from google.protobuf import struct_pb2 as struct # type: ignore @@ -38,16 +38,12 @@ "UpdateParticipantRequest", "InputText", "InputAudio", - "AudioInput", "OutputAudio", "AutomatedAgentReply", "SuggestionFeature", "AnalyzeContentRequest", "DtmfParameters", "AnalyzeContentResponse", - "InputTextConfig", - "StreamingAnalyzeContentRequest", - "StreamingAnalyzeContentResponse", "AnnotatedMessagePart", "MessageAnnotation", "ArticleAnswer", @@ -320,29 +316,7 @@ class InputAudio(proto.Message): """ config = proto.Field( - proto.MESSAGE, number=1, message=gcd_audio_config.InputAudioConfig, - ) - - audio = proto.Field(proto.BYTES, number=2) - - -class AudioInput(proto.Message): - r"""Represents the natural language speech audio to be processed. - - Attributes: - config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): - Required. Instructs the speech recognizer how - to process the speech audio. - audio (bytes): - Required. The natural language speech audio - to be processed. A single request can contain up - to 1 minute of speech audio data. The - transcribed text cannot contain more than 256 - bytes. - """ - - config = proto.Field( - proto.MESSAGE, number=1, message=gcd_audio_config.InputAudioConfig, + proto.MESSAGE, number=1, message=audio_config.InputAudioConfig, ) audio = proto.Field(proto.BYTES, number=2) @@ -361,7 +335,7 @@ class OutputAudio(proto.Message): """ config = proto.Field( - proto.MESSAGE, number=1, message=gcd_audio_config.OutputAudioConfig, + proto.MESSAGE, number=1, message=audio_config.OutputAudioConfig, ) audio = proto.Field(proto.BYTES, number=2) @@ -436,16 +410,8 @@ class AnalyzeContentRequest(proto.Message): Required. The name of the participant this text comes from. Format: ``projects//locations//conversations//participants/``. - text (google.cloud.dialogflow_v2beta1.types.InputText): - The natural language text to be processed. - audio (google.cloud.dialogflow_v2beta1.types.InputAudio): - The natural language speech audio to be - processed. text_input (google.cloud.dialogflow_v2beta1.types.TextInput): The natural language text to be processed. - audio_input (google.cloud.dialogflow_v2beta1.types.AudioInput): - The natural language speech audio to be - processed. event_input (google.cloud.dialogflow_v2beta1.types.EventInput): An input event to send to Dialogflow. reply_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): @@ -484,24 +450,16 @@ class AnalyzeContentRequest(proto.Message): participant = proto.Field(proto.STRING, number=1) - text = proto.Field(proto.MESSAGE, number=3, oneof="input", message="InputText",) - - audio = proto.Field(proto.MESSAGE, number=4, oneof="input", message="InputAudio",) - text_input = proto.Field( proto.MESSAGE, number=6, oneof="input", message=session.TextInput, ) - audio_input = proto.Field( - proto.MESSAGE, number=7, oneof="input", message="AudioInput", - ) - event_input = proto.Field( proto.MESSAGE, number=8, oneof="input", message=session.EventInput, ) reply_audio_config = proto.Field( - proto.MESSAGE, number=5, message=gcd_audio_config.OutputAudioConfig, + proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) query_params = proto.Field( @@ -596,245 +554,6 @@ class AnalyzeContentResponse(proto.Message): dtmf_parameters = proto.Field(proto.MESSAGE, number=9, message="DtmfParameters",) -class InputTextConfig(proto.Message): - r"""Defines the language used in the input text. - - Attributes: - language_code (str): - Required. The language of this conversational query. See - `Language - Support `__ - for a list of the currently supported language codes. - """ - - language_code = proto.Field(proto.STRING, number=1) - - -class StreamingAnalyzeContentRequest(proto.Message): - r"""The top-level message sent by the client to the - [Participants.StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] - method. - - Multiple request messages should be sent in order: - - 1. The first message must contain - [participant][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.participant], - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - and optionally - [query_params][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.query_params]. - If you want to receive an audio response, it should also contain - [reply_audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.reply_audio_config]. - The message must not contain - [input][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input]. - - 2. If - [config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [audio_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.audio_config], - all subsequent messages must contain - [input_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_audio] - to continue with Speech recognition. If you decide to rather - analyze text input after you already started Speech recognition, - please send a message with - [StreamingAnalyzeContentRequest.input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - - However, note that: - - - Dialogflow will bill you for the audio so far. - - Dialogflow discards all Speech recognition results in favor of - the text input. - - 3. If - [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.config] - in the first message was set to - [StreamingAnalyzeContentRequest.text_config][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.text_config], - then the second message must contain only - [input_text][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentRequest.input_text]. - Moreover, you must not send more than two messages. - - After you sent all input, you must half-close or abort the request - stream. - - Attributes: - participant (str): - Required. The name of the participant this text comes from. - Format: - ``projects//locations//conversations//participants/``. - audio_config (google.cloud.dialogflow_v2beta1.types.InputAudioConfig): - Instructs the speech recognizer how to - process the speech audio. - text_config (google.cloud.dialogflow_v2beta1.types.InputTextConfig): - The natural language text to be processed. - reply_audio_config (google.cloud.dialogflow_v2beta1.types.OutputAudioConfig): - Speech synthesis configuration. - The speech synthesis settings for a virtual - agent that may be configured for the associated - conversation profile are not used when calling - StreamingAnalyzeContent. If this configuration - is not supplied, speech synthesis is disabled. - input_audio (bytes): - The input audio content to be recognized. Must be sent if - ``audio_config`` is set in the first message. The complete - audio over all streaming messages must not exceed 1 minute. - input_text (str): - The UTF-8 encoded natural language text to be processed. - Must be sent if ``text_config`` is set in the first message. - Text length must not exceed 256 bytes. The ``input_text`` - field can be only sent once. - input_dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): - The DTMF digits used to invoke intent and - fill in parameter value. - This input is ignored if the previous response - indicated that DTMF input is not accepted. - query_params (google.cloud.dialogflow_v2beta1.types.QueryParameters): - Parameters for a Dialogflow virtual-agent - query. - enable_extended_streaming (bool): - Enable full bidirectional streaming. You can keep streaming - the audio until timeout, and there's no need to half close - the stream to get the response. - - Restrictions: - - - Timeout: 3 mins. - - Audio Encoding: only supports - [AudioEncoding.AUDIO_ENCODING_LINEAR_16][google.cloud.dialogflow.v2beta1.AudioEncoding.AUDIO_ENCODING_LINEAR_16] - and - [AudioEncoding.AUDIO_ENCODING_MULAW][google.cloud.dialogflow.v2beta1.AudioEncoding.AUDIO_ENCODING_MULAW] - - Lifecycle: conversation should be in ``Assist Stage``, go - to [Conversation.CreateConversation][] for more - information. - - InvalidArgument Error will be returned if the one of - restriction checks failed. - - You can find more details in - https://cloud.google.com/dialogflow/priv/docs/agent-assist/analyze-content-streaming - """ - - participant = proto.Field(proto.STRING, number=1) - - audio_config = proto.Field( - proto.MESSAGE, - number=2, - oneof="config", - message=gcd_audio_config.InputAudioConfig, - ) - - text_config = proto.Field( - proto.MESSAGE, number=3, oneof="config", message="InputTextConfig", - ) - - reply_audio_config = proto.Field( - proto.MESSAGE, number=4, message=gcd_audio_config.OutputAudioConfig, - ) - - input_audio = proto.Field(proto.BYTES, number=5, oneof="input") - - input_text = proto.Field(proto.STRING, number=6, oneof="input") - - input_dtmf = proto.Field( - proto.MESSAGE, - number=9, - oneof="input", - message=gcd_audio_config.TelephonyDtmfEvents, - ) - - query_params = proto.Field( - proto.MESSAGE, number=7, message=session.QueryParameters, - ) - - enable_extended_streaming = proto.Field(proto.BOOL, number=11) - - -class StreamingAnalyzeContentResponse(proto.Message): - r"""The top-level message returned from the ``StreamingAnalyzeContent`` - method. - - Multiple response messages can be returned in order: - - 1. If the input was set to streaming audio, the first one or more - messages contain ``recognition_result``. Each - ``recognition_result`` represents a more complete transcript of - what the user said. The last ``recognition_result`` has - ``is_final`` set to ``true``. - - 2. The next message contains ``reply_text`` and optionally - ``reply_audio`` returned by an agent. This message may also - contain ``automated_agent_reply``. - - Attributes: - recognition_result (google.cloud.dialogflow_v2beta1.types.StreamingRecognitionResult): - The result of speech recognition. - reply_text (str): - Optional. The output text content. - This field is set if an automated agent - responded with a text for the user. - reply_audio (google.cloud.dialogflow_v2beta1.types.OutputAudio): - Optional. The audio data bytes encoded as specified in the - request. This field is set if: - - - The ``reply_audio_config`` field is specified in the - request. - - The automated agent, which this output comes from, - responded with audio. In such case, the - ``reply_audio.config`` field contains settings used to - synthesize the speech. - - In some scenarios, multiple output audio fields may be - present in the response structure. In these cases, only the - top-most-level audio output has content. - automated_agent_reply (google.cloud.dialogflow_v2beta1.types.AutomatedAgentReply): - Optional. Only set if a Dialogflow automated agent has - responded. Note that: - [AutomatedAgentReply.detect_intent_response.output_audio][] - and - [AutomatedAgentReply.detect_intent_response.output_audio_config][] - are always empty, use - [reply_audio][google.cloud.dialogflow.v2beta1.StreamingAnalyzeContentResponse.reply_audio] - instead. - message (google.cloud.dialogflow_v2beta1.types.Message): - Output only. Message analyzed by CCAI. - human_agent_suggestion_results (Sequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestions for most recent human agent. The order is - the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.human_agent_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.human_agent_suggestion_config]. - end_user_suggestion_results (Sequence[google.cloud.dialogflow_v2beta1.types.SuggestionResult]): - The suggestions for end user. The order is the same as - [HumanAgentAssistantConfig.SuggestionConfig.feature_configs][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.SuggestionConfig.feature_configs] - of - [HumanAgentAssistantConfig.end_user_suggestion_config][google.cloud.dialogflow.v2beta1.HumanAgentAssistantConfig.end_user_suggestion_config]. - dtmf_parameters (google.cloud.dialogflow_v2beta1.types.DtmfParameters): - Indicates the parameters of DTMF. - """ - - recognition_result = proto.Field( - proto.MESSAGE, number=1, message=session.StreamingRecognitionResult, - ) - - reply_text = proto.Field(proto.STRING, number=2) - - reply_audio = proto.Field(proto.MESSAGE, number=3, message="OutputAudio",) - - automated_agent_reply = proto.Field( - proto.MESSAGE, number=4, message="AutomatedAgentReply", - ) - - message = proto.Field(proto.MESSAGE, number=6, message="Message",) - - human_agent_suggestion_results = proto.RepeatedField( - proto.MESSAGE, number=7, message="SuggestionResult", - ) - - end_user_suggestion_results = proto.RepeatedField( - proto.MESSAGE, number=8, message="SuggestionResult", - ) - - dtmf_parameters = proto.Field(proto.MESSAGE, number=10, message="DtmfParameters",) - - class AnnotatedMessagePart(proto.Message): r"""Represents a part of a message possibly annotated with an entity. The part can be an entity or purely a part of the diff --git a/google/cloud/dialogflow_v2beta1/types/session.py b/google/cloud/dialogflow_v2beta1/types/session.py index 435e12e36..83f336c1d 100644 --- a/google/cloud/dialogflow_v2beta1/types/session.py +++ b/google/cloud/dialogflow_v2beta1/types/session.py @@ -293,6 +293,9 @@ class QueryInput(proto.Message): The natural language text to be processed. event (google.cloud.dialogflow_v2beta1.types.EventInput): The event to be processed. + dtmf (google.cloud.dialogflow_v2beta1.types.TelephonyDtmfEvents): + The DTMF digits used to invoke intent and + fill in parameter value. """ audio_config = proto.Field( @@ -306,6 +309,13 @@ class QueryInput(proto.Message): event = proto.Field(proto.MESSAGE, number=3, oneof="input", message="EventInput",) + dtmf = proto.Field( + proto.MESSAGE, + number=4, + oneof="input", + message=gcd_audio_config.TelephonyDtmfEvents, + ) + class QueryResult(proto.Message): r"""Represents the result of conversational query or event diff --git a/noxfile.py b/noxfile.py index 0ad24c69c..8e4c5018f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -18,6 +18,7 @@ from __future__ import absolute_import import os +import pathlib import shutil import nox @@ -30,6 +31,8 @@ SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + # 'docfx' is excluded since it only needs to run in 'docs-presubmit' nox.options.sessions = [ "unit", @@ -41,6 +44,9 @@ "docs", ] +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + @nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): @@ -81,13 +87,15 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("asyncmock", "pytest-asyncio") - session.install( - "mock", "pytest", "pytest-cov", + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) + session.install("asyncmock", "pytest-asyncio", "-c", constraints_path) - session.install("-e", ".") + session.install("mock", "pytest", "pytest-cov", "-c", constraints_path) + + session.install("-e", ".", "-c", constraints_path) # Run py.test against the unit tests. session.run( @@ -114,6 +122,9 @@ def unit(session): @nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") @@ -138,10 +149,8 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install( - "mock", "pytest", "google-cloud-testutils", - ) - session.install("-e", ".") + session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path) + session.install("-e", ".", "-c", constraints_path) # Run py.test against the system tests. if system_test_exists: @@ -170,7 +179,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=99") + session.run("coverage", "report", "--show-missing", "--fail-under=98") session.run("coverage", "erase") @@ -201,9 +210,7 @@ def docfx(session): """Build the docfx yaml files for this library.""" session.install("-e", ".") - # sphinx-docfx-yaml supports up to sphinx version 1.5.5. - # https://github.com/docascode/sphinx-docfx-yaml/issues/97 - session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + session.install("sphinx", "alabaster", "recommonmark", "gcp-sphinx-docfx-yaml") shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( diff --git a/renovate.json b/renovate.json index 4fa949311..f08bc22c9 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,6 @@ { "extends": [ "config:base", ":preserveSemverRanges" - ] + ], + "ignorePaths": [".pre-commit-config.yaml"] } diff --git a/scripts/fixup_dialogflow_v2_keywords.py b/scripts/fixup_dialogflow_v2_keywords.py index 3866fb44a..a6f9a0f0c 100644 --- a/scripts/fixup_dialogflow_v2_keywords.py +++ b/scripts/fixup_dialogflow_v2_keywords.py @@ -41,7 +41,7 @@ def partition( class dialogflowCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text_input', 'audio_input', 'event_input', 'reply_audio_config', 'query_params', 'request_id', ), + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'request_id', ), 'batch_create_entities': ('parent', 'entities', 'language_code', ), 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), 'batch_delete_entity_types': ('parent', 'entity_type_names', ), @@ -50,7 +50,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), 'complete_conversation': ('name', ), - 'create_call_matcher': ('parent', 'call_matcher', ), 'create_context': ('parent', 'context', ), 'create_conversation': ('parent', 'conversation', 'conversation_id', ), 'create_conversation_profile': ('parent', 'conversation_profile', ), @@ -62,7 +61,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'create_session_entity_type': ('parent', 'session_entity_type', ), 'delete_agent': ('parent', ), 'delete_all_contexts': ('parent', ), - 'delete_call_matcher': ('name', ), 'delete_context': ('name', ), 'delete_conversation_profile': ('name', ), 'delete_document': ('name', ), @@ -85,7 +83,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'get_validation_result': ('parent', 'language_code', ), 'import_agent': ('parent', 'agent_uri', 'agent_content', ), 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_call_matchers': ('parent', 'page_size', 'page_token', ), 'list_contexts': ('parent', 'page_size', 'page_token', ), 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), @@ -101,7 +98,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), 'search_agents': ('parent', 'page_size', 'page_token', ), 'set_agent': ('agent', 'update_mask', ), - 'streaming_analyze_content': ('participant', 'audio_config', 'text_config', 'reply_audio_config', 'input_audio', 'input_text', 'input_dtmf', 'query_params', ), 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), 'suggest_articles': ('parent', 'latest_message', 'context_size', ), 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), diff --git a/scripts/fixup_dialogflow_v2beta1_keywords.py b/scripts/fixup_dialogflow_v2beta1_keywords.py index 7d019940b..edac9dea1 100644 --- a/scripts/fixup_dialogflow_v2beta1_keywords.py +++ b/scripts/fixup_dialogflow_v2beta1_keywords.py @@ -41,7 +41,7 @@ def partition( class dialogflowCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text', 'audio', 'text_input', 'audio_input', 'event_input', 'reply_audio_config', 'query_params', 'message_send_time', 'request_id', ), + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'message_send_time', 'request_id', ), 'batch_create_entities': ('parent', 'entities', 'language_code', ), 'batch_create_messages': ('parent', 'requests', ), 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), @@ -52,7 +52,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), 'complete_conversation': ('name', ), - 'create_call_matcher': ('parent', 'call_matcher', ), 'create_context': ('parent', 'context', ), 'create_conversation': ('parent', 'conversation', 'conversation_id', ), 'create_conversation_profile': ('parent', 'conversation_profile', ), @@ -64,7 +63,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'create_session_entity_type': ('parent', 'session_entity_type', ), 'delete_agent': ('parent', ), 'delete_all_contexts': ('parent', ), - 'delete_call_matcher': ('name', ), 'delete_context': ('name', ), 'delete_conversation_profile': ('name', ), 'delete_document': ('name', ), @@ -89,7 +87,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'import_agent': ('parent', 'agent_uri', 'agent_content', ), 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), 'list_answer_records': ('parent', 'page_size', 'page_token', ), - 'list_call_matchers': ('parent', 'page_size', 'page_token', ), 'list_contexts': ('parent', 'page_size', 'page_token', ), 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), @@ -106,7 +103,6 @@ class dialogflowCallTransformer(cst.CSTTransformer): 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), 'search_agents': ('parent', 'page_size', 'page_token', ), 'set_agent': ('agent', 'update_mask', ), - 'streaming_analyze_content': ('participant', 'audio_config', 'text_config', 'reply_audio_config', 'input_audio', 'input_text', 'input_dtmf', 'query_params', 'enable_extended_streaming', ), 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), 'suggest_articles': ('parent', 'latest_message', 'context_size', ), 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), diff --git a/setup.py b/setup.py index 84895e0e6..91e165a4d 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ description = "Client library for the Dialogflow API" version = "2.1.0" release_status = "Development Status :: 5 - Production/Stable" -dependencies = ["google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "proto-plus >= 1.10.0"] +dependencies = ["google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.10.0"] package_root = os.path.abspath(os.path.dirname(__file__)) diff --git a/synth.metadata b/synth.metadata index 6a06ead8c..72c091c09 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-dialogflow.git", - "sha": "4717cb2deeabf8a4226b27c9912cc809c5804936" + "remote": "git@github.com:googleapis/python-dialogflow", + "sha": "e5314e6c933b829df784ed4ffec3b93c1bd7ca63" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "4b16c60a8fffe213d3a5002f85696fef2b6a8172", - "internalRef": "362090097" + "sha": "915925089600094e72e4bfa8cf586c170e6b7109", + "internalRef": "366152684" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "ac8f20f12e7a4c0b0ae1c6fa415f684a25ea82b7" + "sha": "6d76df2138f8f841e5a5b9ac427f81def520c15f" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "ac8f20f12e7a4c0b0ae1c6fa415f684a25ea82b7" + "sha": "6d76df2138f8f841e5a5b9ac427f81def520c15f" } } ], @@ -49,428 +49,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/header-checker-lint.yml", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/dialogflow_v2/agents.rst", - "docs/dialogflow_v2/answer_records.rst", - "docs/dialogflow_v2/contexts.rst", - "docs/dialogflow_v2/conversation_profiles.rst", - "docs/dialogflow_v2/conversations.rst", - "docs/dialogflow_v2/documents.rst", - "docs/dialogflow_v2/entity_types.rst", - "docs/dialogflow_v2/environments.rst", - "docs/dialogflow_v2/intents.rst", - "docs/dialogflow_v2/knowledge_bases.rst", - "docs/dialogflow_v2/participants.rst", - "docs/dialogflow_v2/services.rst", - "docs/dialogflow_v2/session_entity_types.rst", - "docs/dialogflow_v2/sessions.rst", - "docs/dialogflow_v2/types.rst", - "docs/dialogflow_v2beta1/agents.rst", - "docs/dialogflow_v2beta1/answer_records.rst", - "docs/dialogflow_v2beta1/contexts.rst", - "docs/dialogflow_v2beta1/conversation_profiles.rst", - "docs/dialogflow_v2beta1/conversations.rst", - "docs/dialogflow_v2beta1/documents.rst", - "docs/dialogflow_v2beta1/entity_types.rst", - "docs/dialogflow_v2beta1/environments.rst", - "docs/dialogflow_v2beta1/intents.rst", - "docs/dialogflow_v2beta1/knowledge_bases.rst", - "docs/dialogflow_v2beta1/participants.rst", - "docs/dialogflow_v2beta1/services.rst", - "docs/dialogflow_v2beta1/session_entity_types.rst", - "docs/dialogflow_v2beta1/sessions.rst", - "docs/dialogflow_v2beta1/types.rst", - "docs/multiprocessing.rst", - "google/cloud/dialogflow/__init__.py", - "google/cloud/dialogflow/py.typed", - "google/cloud/dialogflow_v2/__init__.py", - "google/cloud/dialogflow_v2/proto/agent.proto", - "google/cloud/dialogflow_v2/proto/answer_record.proto", - "google/cloud/dialogflow_v2/proto/audio_config.proto", - "google/cloud/dialogflow_v2/proto/context.proto", - "google/cloud/dialogflow_v2/proto/conversation.proto", - "google/cloud/dialogflow_v2/proto/conversation_event.proto", - "google/cloud/dialogflow_v2/proto/conversation_profile.proto", - "google/cloud/dialogflow_v2/proto/document.proto", - "google/cloud/dialogflow_v2/proto/entity_type.proto", - "google/cloud/dialogflow_v2/proto/environment.proto", - "google/cloud/dialogflow_v2/proto/gcs.proto", - "google/cloud/dialogflow_v2/proto/human_agent_assistant_event.proto", - "google/cloud/dialogflow_v2/proto/intent.proto", - "google/cloud/dialogflow_v2/proto/knowledge_base.proto", - "google/cloud/dialogflow_v2/proto/participant.proto", - "google/cloud/dialogflow_v2/proto/session.proto", - "google/cloud/dialogflow_v2/proto/session_entity_type.proto", - "google/cloud/dialogflow_v2/proto/validation_result.proto", - "google/cloud/dialogflow_v2/proto/webhook.proto", - "google/cloud/dialogflow_v2/py.typed", - "google/cloud/dialogflow_v2/services/__init__.py", - "google/cloud/dialogflow_v2/services/agents/__init__.py", - "google/cloud/dialogflow_v2/services/agents/async_client.py", - "google/cloud/dialogflow_v2/services/agents/client.py", - "google/cloud/dialogflow_v2/services/agents/pagers.py", - "google/cloud/dialogflow_v2/services/agents/transports/__init__.py", - "google/cloud/dialogflow_v2/services/agents/transports/base.py", - "google/cloud/dialogflow_v2/services/agents/transports/grpc.py", - "google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/answer_records/__init__.py", - "google/cloud/dialogflow_v2/services/answer_records/async_client.py", - "google/cloud/dialogflow_v2/services/answer_records/client.py", - "google/cloud/dialogflow_v2/services/answer_records/pagers.py", - "google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py", - "google/cloud/dialogflow_v2/services/answer_records/transports/base.py", - "google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py", - "google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/contexts/__init__.py", - "google/cloud/dialogflow_v2/services/contexts/async_client.py", - "google/cloud/dialogflow_v2/services/contexts/client.py", - "google/cloud/dialogflow_v2/services/contexts/pagers.py", - "google/cloud/dialogflow_v2/services/contexts/transports/__init__.py", - "google/cloud/dialogflow_v2/services/contexts/transports/base.py", - "google/cloud/dialogflow_v2/services/contexts/transports/grpc.py", - "google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/client.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py", - "google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/conversations/__init__.py", - "google/cloud/dialogflow_v2/services/conversations/async_client.py", - "google/cloud/dialogflow_v2/services/conversations/client.py", - "google/cloud/dialogflow_v2/services/conversations/pagers.py", - "google/cloud/dialogflow_v2/services/conversations/transports/__init__.py", - "google/cloud/dialogflow_v2/services/conversations/transports/base.py", - "google/cloud/dialogflow_v2/services/conversations/transports/grpc.py", - "google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/documents/__init__.py", - "google/cloud/dialogflow_v2/services/documents/async_client.py", - "google/cloud/dialogflow_v2/services/documents/client.py", - "google/cloud/dialogflow_v2/services/documents/pagers.py", - "google/cloud/dialogflow_v2/services/documents/transports/__init__.py", - "google/cloud/dialogflow_v2/services/documents/transports/base.py", - "google/cloud/dialogflow_v2/services/documents/transports/grpc.py", - "google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/entity_types/__init__.py", - "google/cloud/dialogflow_v2/services/entity_types/async_client.py", - "google/cloud/dialogflow_v2/services/entity_types/client.py", - "google/cloud/dialogflow_v2/services/entity_types/pagers.py", - "google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py", - "google/cloud/dialogflow_v2/services/entity_types/transports/base.py", - "google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py", - "google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/environments/__init__.py", - "google/cloud/dialogflow_v2/services/environments/async_client.py", - "google/cloud/dialogflow_v2/services/environments/client.py", - "google/cloud/dialogflow_v2/services/environments/pagers.py", - "google/cloud/dialogflow_v2/services/environments/transports/__init__.py", - "google/cloud/dialogflow_v2/services/environments/transports/base.py", - "google/cloud/dialogflow_v2/services/environments/transports/grpc.py", - "google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/intents/__init__.py", - "google/cloud/dialogflow_v2/services/intents/async_client.py", - "google/cloud/dialogflow_v2/services/intents/client.py", - "google/cloud/dialogflow_v2/services/intents/pagers.py", - "google/cloud/dialogflow_v2/services/intents/transports/__init__.py", - "google/cloud/dialogflow_v2/services/intents/transports/base.py", - "google/cloud/dialogflow_v2/services/intents/transports/grpc.py", - "google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/client.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py", - "google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/participants/__init__.py", - "google/cloud/dialogflow_v2/services/participants/async_client.py", - "google/cloud/dialogflow_v2/services/participants/client.py", - "google/cloud/dialogflow_v2/services/participants/pagers.py", - "google/cloud/dialogflow_v2/services/participants/transports/__init__.py", - "google/cloud/dialogflow_v2/services/participants/transports/base.py", - "google/cloud/dialogflow_v2/services/participants/transports/grpc.py", - "google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/session_entity_types/__init__.py", - "google/cloud/dialogflow_v2/services/session_entity_types/async_client.py", - "google/cloud/dialogflow_v2/services/session_entity_types/client.py", - "google/cloud/dialogflow_v2/services/session_entity_types/pagers.py", - "google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py", - "google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py", - "google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py", - "google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/services/sessions/__init__.py", - "google/cloud/dialogflow_v2/services/sessions/async_client.py", - "google/cloud/dialogflow_v2/services/sessions/client.py", - "google/cloud/dialogflow_v2/services/sessions/transports/__init__.py", - "google/cloud/dialogflow_v2/services/sessions/transports/base.py", - "google/cloud/dialogflow_v2/services/sessions/transports/grpc.py", - "google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2/types/__init__.py", - "google/cloud/dialogflow_v2/types/agent.py", - "google/cloud/dialogflow_v2/types/answer_record.py", - "google/cloud/dialogflow_v2/types/audio_config.py", - "google/cloud/dialogflow_v2/types/context.py", - "google/cloud/dialogflow_v2/types/conversation.py", - "google/cloud/dialogflow_v2/types/conversation_event.py", - "google/cloud/dialogflow_v2/types/conversation_profile.py", - "google/cloud/dialogflow_v2/types/document.py", - "google/cloud/dialogflow_v2/types/entity_type.py", - "google/cloud/dialogflow_v2/types/environment.py", - "google/cloud/dialogflow_v2/types/gcs.py", - "google/cloud/dialogflow_v2/types/human_agent_assistant_event.py", - "google/cloud/dialogflow_v2/types/intent.py", - "google/cloud/dialogflow_v2/types/knowledge_base.py", - "google/cloud/dialogflow_v2/types/participant.py", - "google/cloud/dialogflow_v2/types/session.py", - "google/cloud/dialogflow_v2/types/session_entity_type.py", - "google/cloud/dialogflow_v2/types/validation_result.py", - "google/cloud/dialogflow_v2/types/webhook.py", - "google/cloud/dialogflow_v2beta1/__init__.py", - "google/cloud/dialogflow_v2beta1/proto/agent.proto", - "google/cloud/dialogflow_v2beta1/proto/answer_record.proto", - "google/cloud/dialogflow_v2beta1/proto/audio_config.proto", - "google/cloud/dialogflow_v2beta1/proto/context.proto", - "google/cloud/dialogflow_v2beta1/proto/conversation.proto", - "google/cloud/dialogflow_v2beta1/proto/conversation_event.proto", - "google/cloud/dialogflow_v2beta1/proto/conversation_profile.proto", - "google/cloud/dialogflow_v2beta1/proto/document.proto", - "google/cloud/dialogflow_v2beta1/proto/entity_type.proto", - "google/cloud/dialogflow_v2beta1/proto/environment.proto", - "google/cloud/dialogflow_v2beta1/proto/gcs.proto", - "google/cloud/dialogflow_v2beta1/proto/human_agent_assistant_event.proto", - "google/cloud/dialogflow_v2beta1/proto/intent.proto", - "google/cloud/dialogflow_v2beta1/proto/knowledge_base.proto", - "google/cloud/dialogflow_v2beta1/proto/participant.proto", - "google/cloud/dialogflow_v2beta1/proto/session.proto", - "google/cloud/dialogflow_v2beta1/proto/session_entity_type.proto", - "google/cloud/dialogflow_v2beta1/proto/validation_result.proto", - "google/cloud/dialogflow_v2beta1/proto/webhook.proto", - "google/cloud/dialogflow_v2beta1/py.typed", - "google/cloud/dialogflow_v2beta1/services/__init__.py", - "google/cloud/dialogflow_v2beta1/services/agents/__init__.py", - "google/cloud/dialogflow_v2beta1/services/agents/async_client.py", - "google/cloud/dialogflow_v2beta1/services/agents/client.py", - "google/cloud/dialogflow_v2beta1/services/agents/pagers.py", - "google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/agents/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/client.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/contexts/__init__.py", - "google/cloud/dialogflow_v2beta1/services/contexts/async_client.py", - "google/cloud/dialogflow_v2beta1/services/contexts/client.py", - "google/cloud/dialogflow_v2beta1/services/contexts/pagers.py", - "google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/conversations/__init__.py", - "google/cloud/dialogflow_v2beta1/services/conversations/async_client.py", - "google/cloud/dialogflow_v2beta1/services/conversations/client.py", - "google/cloud/dialogflow_v2beta1/services/conversations/pagers.py", - "google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/documents/__init__.py", - "google/cloud/dialogflow_v2beta1/services/documents/async_client.py", - "google/cloud/dialogflow_v2beta1/services/documents/client.py", - "google/cloud/dialogflow_v2beta1/services/documents/pagers.py", - "google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/documents/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/client.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/environments/__init__.py", - "google/cloud/dialogflow_v2beta1/services/environments/async_client.py", - "google/cloud/dialogflow_v2beta1/services/environments/client.py", - "google/cloud/dialogflow_v2beta1/services/environments/pagers.py", - "google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/environments/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/intents/__init__.py", - "google/cloud/dialogflow_v2beta1/services/intents/async_client.py", - "google/cloud/dialogflow_v2beta1/services/intents/client.py", - "google/cloud/dialogflow_v2beta1/services/intents/pagers.py", - "google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/intents/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/participants/__init__.py", - "google/cloud/dialogflow_v2beta1/services/participants/async_client.py", - "google/cloud/dialogflow_v2beta1/services/participants/client.py", - "google/cloud/dialogflow_v2beta1/services/participants/pagers.py", - "google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/participants/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/services/sessions/__init__.py", - "google/cloud/dialogflow_v2beta1/services/sessions/async_client.py", - "google/cloud/dialogflow_v2beta1/services/sessions/client.py", - "google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py", - "google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py", - "google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py", - "google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py", - "google/cloud/dialogflow_v2beta1/types/__init__.py", - "google/cloud/dialogflow_v2beta1/types/agent.py", - "google/cloud/dialogflow_v2beta1/types/answer_record.py", - "google/cloud/dialogflow_v2beta1/types/audio_config.py", - "google/cloud/dialogflow_v2beta1/types/context.py", - "google/cloud/dialogflow_v2beta1/types/conversation.py", - "google/cloud/dialogflow_v2beta1/types/conversation_event.py", - "google/cloud/dialogflow_v2beta1/types/conversation_profile.py", - "google/cloud/dialogflow_v2beta1/types/document.py", - "google/cloud/dialogflow_v2beta1/types/entity_type.py", - "google/cloud/dialogflow_v2beta1/types/environment.py", - "google/cloud/dialogflow_v2beta1/types/gcs.py", - "google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py", - "google/cloud/dialogflow_v2beta1/types/intent.py", - "google/cloud/dialogflow_v2beta1/types/knowledge_base.py", - "google/cloud/dialogflow_v2beta1/types/participant.py", - "google/cloud/dialogflow_v2beta1/types/session.py", - "google/cloud/dialogflow_v2beta1/types/session_entity_type.py", - "google/cloud/dialogflow_v2beta1/types/validation_result.py", - "google/cloud/dialogflow_v2beta1/types/webhook.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "scripts/decrypt-secrets.sh", - "scripts/fixup_dialogflow_v2_keywords.py", - "scripts/fixup_dialogflow_v2beta1_keywords.py", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/dialogflow_v2/__init__.py", - "tests/unit/gapic/dialogflow_v2/test_agents.py", - "tests/unit/gapic/dialogflow_v2/test_answer_records.py", - "tests/unit/gapic/dialogflow_v2/test_contexts.py", - "tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py", - "tests/unit/gapic/dialogflow_v2/test_conversations.py", - "tests/unit/gapic/dialogflow_v2/test_documents.py", - "tests/unit/gapic/dialogflow_v2/test_entity_types.py", - "tests/unit/gapic/dialogflow_v2/test_environments.py", - "tests/unit/gapic/dialogflow_v2/test_intents.py", - "tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py", - "tests/unit/gapic/dialogflow_v2/test_participants.py", - "tests/unit/gapic/dialogflow_v2/test_session_entity_types.py", - "tests/unit/gapic/dialogflow_v2/test_sessions.py", - "tests/unit/gapic/dialogflow_v2beta1/__init__.py", - "tests/unit/gapic/dialogflow_v2beta1/test_agents.py", - "tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py", - "tests/unit/gapic/dialogflow_v2beta1/test_contexts.py", - "tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py", - "tests/unit/gapic/dialogflow_v2beta1/test_conversations.py", - "tests/unit/gapic/dialogflow_v2beta1/test_documents.py", - "tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py", - "tests/unit/gapic/dialogflow_v2beta1/test_environments.py", - "tests/unit/gapic/dialogflow_v2beta1/test_intents.py", - "tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py", - "tests/unit/gapic/dialogflow_v2beta1/test_participants.py", - "tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py", - "tests/unit/gapic/dialogflow_v2beta1/test_sessions.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index 602691e48..13fd47bae 100644 --- a/synth.py +++ b/synth.py @@ -39,8 +39,8 @@ templated_files = common.py_library( samples=False, # set to True only if there are samples microgenerator=True, - cov_level=99, - + cov_level=98, + ) s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file @@ -51,5 +51,5 @@ '''["']-W["'], # warnings as errors''', "", ) - + s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 04d54afee..25cd0683d 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -1,9 +1,9 @@ # This constraints file is used to check that lower bounds # are correct in setup.py -# List *all* library dependencies and extras in this file. +# List all library dependencies and extras in this file. # Pin the version to the lower bound. -# -# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", -# Then this file should have foo==1.14.0 -google-api-core==1.22.0 + +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.22.2 proto-plus==1.10.0 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index e69de29bb..da93009be 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index e69de29bb..da93009be 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index e69de29bb..da93009be 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -0,0 +1,2 @@ +# This constraints file is left inentionally empty +# so the latest version of dependencies is installed \ No newline at end of file diff --git a/tests/unit/gapic/dialogflow_v2/test_conversations.py b/tests/unit/gapic/dialogflow_v2/test_conversations.py index 2fedf55b8..2f3f7b185 100644 --- a/tests/unit/gapic/dialogflow_v2/test_conversations.py +++ b/tests/unit/gapic/dialogflow_v2/test_conversations.py @@ -1599,852 +1599,6 @@ async def test_complete_conversation_flattened_error_async(): ) -def test_create_call_matcher( - transport: str = "grpc", request_type=conversation.CreateCallMatcherRequest -): - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.CallMatcher( - name="name_value", - to_header="to_header_value", - from_header="from_header_value", - call_id_header="call_id_header_value", - ) - - response = client.create_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.CreateCallMatcherRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, conversation.CallMatcher) - - assert response.name == "name_value" - - assert response.to_header == "to_header_value" - - assert response.from_header == "from_header_value" - - assert response.call_id_header == "call_id_header_value" - - -def test_create_call_matcher_from_dict(): - test_create_call_matcher(request_type=dict) - - -def test_create_call_matcher_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - client.create_call_matcher() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.CreateCallMatcherRequest() - - -@pytest.mark.asyncio -async def test_create_call_matcher_async( - transport: str = "grpc_asyncio", request_type=conversation.CreateCallMatcherRequest -): - client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.CallMatcher( - name="name_value", - to_header="to_header_value", - from_header="from_header_value", - call_id_header="call_id_header_value", - ) - ) - - response = await client.create_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.CreateCallMatcherRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.CallMatcher) - - assert response.name == "name_value" - - assert response.to_header == "to_header_value" - - assert response.from_header == "from_header_value" - - assert response.call_id_header == "call_id_header_value" - - -@pytest.mark.asyncio -async def test_create_call_matcher_async_from_dict(): - await test_create_call_matcher_async(request_type=dict) - - -def test_create_call_matcher_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.CreateCallMatcherRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - call.return_value = conversation.CallMatcher() - - client.create_call_matcher(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_call_matcher_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.CreateCallMatcherRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.CallMatcher() - ) - - await client.create_call_matcher(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_call_matcher_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.CallMatcher() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_call_matcher( - parent="parent_value", - call_matcher=conversation.CallMatcher(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] - - assert args[0].parent == "parent_value" - - assert args[0].call_matcher == conversation.CallMatcher(name="name_value") - - -def test_create_call_matcher_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_call_matcher( - conversation.CreateCallMatcherRequest(), - parent="parent_value", - call_matcher=conversation.CallMatcher(name="name_value"), - ) - - -@pytest.mark.asyncio -async def test_create_call_matcher_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.CallMatcher() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.CallMatcher() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_call_matcher( - parent="parent_value", - call_matcher=conversation.CallMatcher(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] - - assert args[0].parent == "parent_value" - - assert args[0].call_matcher == conversation.CallMatcher(name="name_value") - - -@pytest.mark.asyncio -async def test_create_call_matcher_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_call_matcher( - conversation.CreateCallMatcherRequest(), - parent="parent_value", - call_matcher=conversation.CallMatcher(name="name_value"), - ) - - -def test_list_call_matchers( - transport: str = "grpc", request_type=conversation.ListCallMatchersRequest -): - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListCallMatchersResponse( - next_page_token="next_page_token_value", - ) - - response = client.list_call_matchers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.ListCallMatchersRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListCallMatchersPager) - - assert response.next_page_token == "next_page_token_value" - - -def test_list_call_matchers_from_dict(): - test_list_call_matchers(request_type=dict) - - -def test_list_call_matchers_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - client.list_call_matchers() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.ListCallMatchersRequest() - - -@pytest.mark.asyncio -async def test_list_call_matchers_async( - transport: str = "grpc_asyncio", request_type=conversation.ListCallMatchersRequest -): - client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.ListCallMatchersResponse( - next_page_token="next_page_token_value", - ) - ) - - response = await client.list_call_matchers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.ListCallMatchersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCallMatchersAsyncPager) - - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.asyncio -async def test_list_call_matchers_async_from_dict(): - await test_list_call_matchers_async(request_type=dict) - - -def test_list_call_matchers_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.ListCallMatchersRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - call.return_value = conversation.ListCallMatchersResponse() - - client.list_call_matchers(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_call_matchers_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.ListCallMatchersRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.ListCallMatchersResponse() - ) - - await client.list_call_matchers(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_call_matchers_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListCallMatchersResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_call_matchers(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] - - assert args[0].parent == "parent_value" - - -def test_list_call_matchers_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_call_matchers( - conversation.ListCallMatchersRequest(), parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_call_matchers_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListCallMatchersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.ListCallMatchersResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_call_matchers(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] - - assert args[0].parent == "parent_value" - - -@pytest.mark.asyncio -async def test_list_call_matchers_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_call_matchers( - conversation.ListCallMatchersRequest(), parent="parent_value", - ) - - -def test_list_call_matchers_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_call_matchers(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, conversation.CallMatcher) for i in results) - - -def test_list_call_matchers_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - pages = list(client.list_call_matchers(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_call_matchers_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - async_pager = await client.list_call_matchers(request={},) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.CallMatcher) for i in responses) - - -@pytest.mark.asyncio -async def test_list_call_matchers_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_call_matchers(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_call_matcher( - transport: str = "grpc", request_type=conversation.DeleteCallMatcherRequest -): - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.DeleteCallMatcherRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_call_matcher_from_dict(): - test_delete_call_matcher(request_type=dict) - - -def test_delete_call_matcher_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - client.delete_call_matcher() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.DeleteCallMatcherRequest() - - -@pytest.mark.asyncio -async def test_delete_call_matcher_async( - transport: str = "grpc_asyncio", request_type=conversation.DeleteCallMatcherRequest -): - client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.delete_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.DeleteCallMatcherRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_call_matcher_async_from_dict(): - await test_delete_call_matcher_async(request_type=dict) - - -def test_delete_call_matcher_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.DeleteCallMatcherRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - call.return_value = None - - client.delete_call_matcher(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_call_matcher_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.DeleteCallMatcherRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.delete_call_matcher(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_call_matcher_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__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_call_matcher(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] - - assert args[0].name == "name_value" - - -def test_delete_call_matcher_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_call_matcher( - conversation.DeleteCallMatcherRequest(), name="name_value", - ) - - -@pytest.mark.asyncio -async def test_delete_call_matcher_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__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_call_matcher(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] - - assert args[0].name == "name_value" - - -@pytest.mark.asyncio -async def test_delete_call_matcher_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_call_matcher( - conversation.DeleteCallMatcherRequest(), name="name_value", - ) - - def test_list_messages( transport: str = "grpc", request_type=conversation.ListMessagesRequest ): @@ -2893,9 +2047,6 @@ def test_conversations_base_transport(): "list_conversations", "get_conversation", "complete_conversation", - "create_call_matcher", - "list_call_matchers", - "delete_call_matcher", "list_messages", ) for method in methods: @@ -3163,34 +2314,9 @@ def test_conversations_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel -def test_call_matcher_path(): +def test_conversation_path(): project = "squid" conversation = "clam" - call_matcher = "whelk" - - expected = "projects/{project}/conversations/{conversation}/callMatchers/{call_matcher}".format( - project=project, conversation=conversation, call_matcher=call_matcher, - ) - actual = ConversationsClient.call_matcher_path(project, conversation, call_matcher) - assert expected == actual - - -def test_parse_call_matcher_path(): - expected = { - "project": "octopus", - "conversation": "oyster", - "call_matcher": "nudibranch", - } - path = ConversationsClient.call_matcher_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_call_matcher_path(path) - assert expected == actual - - -def test_conversation_path(): - project = "cuttlefish" - conversation = "mussel" expected = "projects/{project}/conversations/{conversation}".format( project=project, conversation=conversation, @@ -3201,8 +2327,8 @@ def test_conversation_path(): def test_parse_conversation_path(): expected = { - "project": "winkle", - "conversation": "nautilus", + "project": "whelk", + "conversation": "octopus", } path = ConversationsClient.conversation_path(**expected) @@ -3212,8 +2338,8 @@ def test_parse_conversation_path(): def test_conversation_profile_path(): - project = "scallop" - conversation_profile = "abalone" + project = "oyster" + conversation_profile = "nudibranch" expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, @@ -3226,8 +2352,8 @@ def test_conversation_profile_path(): def test_parse_conversation_profile_path(): expected = { - "project": "squid", - "conversation_profile": "clam", + "project": "cuttlefish", + "conversation_profile": "mussel", } path = ConversationsClient.conversation_profile_path(**expected) @@ -3237,9 +2363,9 @@ def test_parse_conversation_profile_path(): def test_message_path(): - project = "whelk" - conversation = "octopus" - message = "oyster" + project = "winkle" + conversation = "nautilus" + message = "scallop" expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, @@ -3250,9 +2376,9 @@ def test_message_path(): def test_parse_message_path(): expected = { - "project": "nudibranch", - "conversation": "cuttlefish", - "message": "mussel", + "project": "abalone", + "conversation": "squid", + "message": "clam", } path = ConversationsClient.message_path(**expected) @@ -3262,7 +2388,7 @@ def test_parse_message_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, @@ -3273,7 +2399,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "octopus", } path = ConversationsClient.common_billing_account_path(**expected) @@ -3283,7 +2409,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "oyster" expected = "folders/{folder}".format(folder=folder,) actual = ConversationsClient.common_folder_path(folder) @@ -3292,7 +2418,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "nudibranch", } path = ConversationsClient.common_folder_path(**expected) @@ -3302,7 +2428,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "cuttlefish" expected = "organizations/{organization}".format(organization=organization,) actual = ConversationsClient.common_organization_path(organization) @@ -3311,7 +2437,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "mussel", } path = ConversationsClient.common_organization_path(**expected) @@ -3321,7 +2447,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "winkle" expected = "projects/{project}".format(project=project,) actual = ConversationsClient.common_project_path(project) @@ -3330,7 +2456,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "nautilus", } path = ConversationsClient.common_project_path(**expected) @@ -3340,8 +2466,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -3352,8 +2478,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "squid", + "location": "clam", } path = ConversationsClient.common_location_path(**expected) diff --git a/tests/unit/gapic/dialogflow_v2/test_participants.py b/tests/unit/gapic/dialogflow_v2/test_participants.py index 705bec0ff..bef06db64 100644 --- a/tests/unit/gapic/dialogflow_v2/test_participants.py +++ b/tests/unit/gapic/dialogflow_v2/test_participants.py @@ -1703,11 +1703,6 @@ def test_analyze_content_flattened(): client.analyze_content( participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) @@ -1731,11 +1726,6 @@ def test_analyze_content_flattened_error(): gcd_participant.AnalyzeContentRequest(), participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) @@ -1757,11 +1747,6 @@ async def test_analyze_content_flattened_async(): response = await client.analyze_content( participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) @@ -1786,95 +1771,10 @@ async def test_analyze_content_flattened_error_async(): gcd_participant.AnalyzeContentRequest(), participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) -def test_streaming_analyze_content( - transport: str = "grpc", request_type=participant.StreamingAnalyzeContentRequest -): - client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_analyze_content), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iter([participant.StreamingAnalyzeContentResponse()]) - - response = client.streaming_analyze_content(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -def test_streaming_analyze_content_from_dict(): - test_streaming_analyze_content(request_type=dict) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async( - transport: str = "grpc_asyncio", - request_type=participant.StreamingAnalyzeContentRequest, -): - client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_analyze_content), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock( - side_effect=[participant.StreamingAnalyzeContentResponse()] - ) - - response = await client.streaming_analyze_content(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async_from_dict(): - await test_streaming_analyze_content_async(request_type=dict) - - def test_suggest_articles( transport: str = "grpc", request_type=participant.SuggestArticlesRequest ): @@ -2421,7 +2321,6 @@ def test_participants_base_transport(): "list_participants", "update_participant", "analyze_content", - "streaming_analyze_content", "suggest_articles", "suggest_faq_answers", ) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py b/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py index 96d430f8a..daa1b4d91 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py @@ -1603,852 +1603,6 @@ async def test_complete_conversation_flattened_error_async(): ) -def test_create_call_matcher( - transport: str = "grpc", request_type=conversation.CreateCallMatcherRequest -): - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.CallMatcher( - name="name_value", - to_header="to_header_value", - from_header="from_header_value", - call_id_header="call_id_header_value", - ) - - response = client.create_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.CreateCallMatcherRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, conversation.CallMatcher) - - assert response.name == "name_value" - - assert response.to_header == "to_header_value" - - assert response.from_header == "from_header_value" - - assert response.call_id_header == "call_id_header_value" - - -def test_create_call_matcher_from_dict(): - test_create_call_matcher(request_type=dict) - - -def test_create_call_matcher_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - client.create_call_matcher() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.CreateCallMatcherRequest() - - -@pytest.mark.asyncio -async def test_create_call_matcher_async( - transport: str = "grpc_asyncio", request_type=conversation.CreateCallMatcherRequest -): - client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.CallMatcher( - name="name_value", - to_header="to_header_value", - from_header="from_header_value", - call_id_header="call_id_header_value", - ) - ) - - response = await client.create_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.CreateCallMatcherRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.CallMatcher) - - assert response.name == "name_value" - - assert response.to_header == "to_header_value" - - assert response.from_header == "from_header_value" - - assert response.call_id_header == "call_id_header_value" - - -@pytest.mark.asyncio -async def test_create_call_matcher_async_from_dict(): - await test_create_call_matcher_async(request_type=dict) - - -def test_create_call_matcher_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.CreateCallMatcherRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - call.return_value = conversation.CallMatcher() - - client.create_call_matcher(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_call_matcher_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.CreateCallMatcherRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.CallMatcher() - ) - - await client.create_call_matcher(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_call_matcher_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.CallMatcher() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_call_matcher( - parent="parent_value", - call_matcher=conversation.CallMatcher(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] - - assert args[0].parent == "parent_value" - - assert args[0].call_matcher == conversation.CallMatcher(name="name_value") - - -def test_create_call_matcher_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_call_matcher( - conversation.CreateCallMatcherRequest(), - parent="parent_value", - call_matcher=conversation.CallMatcher(name="name_value"), - ) - - -@pytest.mark.asyncio -async def test_create_call_matcher_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.CallMatcher() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.CallMatcher() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_call_matcher( - parent="parent_value", - call_matcher=conversation.CallMatcher(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] - - assert args[0].parent == "parent_value" - - assert args[0].call_matcher == conversation.CallMatcher(name="name_value") - - -@pytest.mark.asyncio -async def test_create_call_matcher_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_call_matcher( - conversation.CreateCallMatcherRequest(), - parent="parent_value", - call_matcher=conversation.CallMatcher(name="name_value"), - ) - - -def test_list_call_matchers( - transport: str = "grpc", request_type=conversation.ListCallMatchersRequest -): - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListCallMatchersResponse( - next_page_token="next_page_token_value", - ) - - response = client.list_call_matchers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.ListCallMatchersRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, pagers.ListCallMatchersPager) - - assert response.next_page_token == "next_page_token_value" - - -def test_list_call_matchers_from_dict(): - test_list_call_matchers(request_type=dict) - - -def test_list_call_matchers_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - client.list_call_matchers() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.ListCallMatchersRequest() - - -@pytest.mark.asyncio -async def test_list_call_matchers_async( - transport: str = "grpc_asyncio", request_type=conversation.ListCallMatchersRequest -): - client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.ListCallMatchersResponse( - next_page_token="next_page_token_value", - ) - ) - - response = await client.list_call_matchers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.ListCallMatchersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCallMatchersAsyncPager) - - assert response.next_page_token == "next_page_token_value" - - -@pytest.mark.asyncio -async def test_list_call_matchers_async_from_dict(): - await test_list_call_matchers_async(request_type=dict) - - -def test_list_call_matchers_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.ListCallMatchersRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - call.return_value = conversation.ListCallMatchersResponse() - - client.list_call_matchers(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_call_matchers_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.ListCallMatchersRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.ListCallMatchersResponse() - ) - - await client.list_call_matchers(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_call_matchers_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListCallMatchersResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_call_matchers(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] - - assert args[0].parent == "parent_value" - - -def test_list_call_matchers_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_call_matchers( - conversation.ListCallMatchersRequest(), parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_call_matchers_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.ListCallMatchersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - conversation.ListCallMatchersResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_call_matchers(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] - - assert args[0].parent == "parent_value" - - -@pytest.mark.asyncio -async def test_list_call_matchers_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_call_matchers( - conversation.ListCallMatchersRequest(), parent="parent_value", - ) - - -def test_list_call_matchers_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_call_matchers(request={}) - - assert pager._metadata == metadata - - results = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, conversation.CallMatcher) for i in results) - - -def test_list_call_matchers_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - pages = list(client.list_call_matchers(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_call_matchers_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - async_pager = await client.list_call_matchers(request={},) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.CallMatcher) for i in responses) - - -@pytest.mark.asyncio -async def test_list_call_matchers_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_call_matchers), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversation.ListCallMatchersResponse( - call_matchers=[ - conversation.CallMatcher(), - conversation.CallMatcher(), - conversation.CallMatcher(), - ], - next_page_token="abc", - ), - conversation.ListCallMatchersResponse( - call_matchers=[], next_page_token="def", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(),], next_page_token="ghi", - ), - conversation.ListCallMatchersResponse( - call_matchers=[conversation.CallMatcher(), conversation.CallMatcher(),], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_call_matchers(request={})).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_call_matcher( - transport: str = "grpc", request_type=conversation.DeleteCallMatcherRequest -): - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.DeleteCallMatcherRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_call_matcher_from_dict(): - test_delete_call_matcher(request_type=dict) - - -def test_delete_call_matcher_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - client.delete_call_matcher() - call.assert_called() - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.DeleteCallMatcherRequest() - - -@pytest.mark.asyncio -async def test_delete_call_matcher_async( - transport: str = "grpc_asyncio", request_type=conversation.DeleteCallMatcherRequest -): - client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - response = await client.delete_call_matcher(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == conversation.DeleteCallMatcherRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_call_matcher_async_from_dict(): - await test_delete_call_matcher_async(request_type=dict) - - -def test_delete_call_matcher_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.DeleteCallMatcherRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - call.return_value = None - - client.delete_call_matcher(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_call_matcher_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversation.DeleteCallMatcherRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - - await client.delete_call_matcher(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_call_matcher_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__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_call_matcher(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] - - assert args[0].name == "name_value" - - -def test_delete_call_matcher_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_call_matcher( - conversation.DeleteCallMatcherRequest(), name="name_value", - ) - - -@pytest.mark.asyncio -async def test_delete_call_matcher_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_call_matcher), "__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_call_matcher(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] - - assert args[0].name == "name_value" - - -@pytest.mark.asyncio -async def test_delete_call_matcher_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_call_matcher( - conversation.DeleteCallMatcherRequest(), name="name_value", - ) - - def test_batch_create_messages( transport: str = "grpc", request_type=conversation.BatchCreateMessagesRequest ): @@ -3115,9 +2269,6 @@ def test_conversations_base_transport(): "list_conversations", "get_conversation", "complete_conversation", - "create_call_matcher", - "list_call_matchers", - "delete_call_matcher", "batch_create_messages", "list_messages", ) @@ -3386,34 +2537,9 @@ def test_conversations_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel -def test_call_matcher_path(): +def test_conversation_path(): project = "squid" conversation = "clam" - call_matcher = "whelk" - - expected = "projects/{project}/conversations/{conversation}/callMatchers/{call_matcher}".format( - project=project, conversation=conversation, call_matcher=call_matcher, - ) - actual = ConversationsClient.call_matcher_path(project, conversation, call_matcher) - assert expected == actual - - -def test_parse_call_matcher_path(): - expected = { - "project": "octopus", - "conversation": "oyster", - "call_matcher": "nudibranch", - } - path = ConversationsClient.call_matcher_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationsClient.parse_call_matcher_path(path) - assert expected == actual - - -def test_conversation_path(): - project = "cuttlefish" - conversation = "mussel" expected = "projects/{project}/conversations/{conversation}".format( project=project, conversation=conversation, @@ -3424,8 +2550,8 @@ def test_conversation_path(): def test_parse_conversation_path(): expected = { - "project": "winkle", - "conversation": "nautilus", + "project": "whelk", + "conversation": "octopus", } path = ConversationsClient.conversation_path(**expected) @@ -3435,8 +2561,8 @@ def test_parse_conversation_path(): def test_conversation_profile_path(): - project = "scallop" - conversation_profile = "abalone" + project = "oyster" + conversation_profile = "nudibranch" expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, @@ -3449,8 +2575,8 @@ def test_conversation_profile_path(): def test_parse_conversation_profile_path(): expected = { - "project": "squid", - "conversation_profile": "clam", + "project": "cuttlefish", + "conversation_profile": "mussel", } path = ConversationsClient.conversation_profile_path(**expected) @@ -3460,9 +2586,9 @@ def test_parse_conversation_profile_path(): def test_message_path(): - project = "whelk" - conversation = "octopus" - message = "oyster" + project = "winkle" + conversation = "nautilus" + message = "scallop" expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, @@ -3473,9 +2599,9 @@ def test_message_path(): def test_parse_message_path(): expected = { - "project": "nudibranch", - "conversation": "cuttlefish", - "message": "mussel", + "project": "abalone", + "conversation": "squid", + "message": "clam", } path = ConversationsClient.message_path(**expected) @@ -3485,7 +2611,7 @@ def test_parse_message_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "whelk" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, @@ -3496,7 +2622,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "octopus", } path = ConversationsClient.common_billing_account_path(**expected) @@ -3506,7 +2632,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "oyster" expected = "folders/{folder}".format(folder=folder,) actual = ConversationsClient.common_folder_path(folder) @@ -3515,7 +2641,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "nudibranch", } path = ConversationsClient.common_folder_path(**expected) @@ -3525,7 +2651,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "cuttlefish" expected = "organizations/{organization}".format(organization=organization,) actual = ConversationsClient.common_organization_path(organization) @@ -3534,7 +2660,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "mussel", } path = ConversationsClient.common_organization_path(**expected) @@ -3544,7 +2670,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "winkle" expected = "projects/{project}".format(project=project,) actual = ConversationsClient.common_project_path(project) @@ -3553,7 +2679,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "nautilus", } path = ConversationsClient.common_project_path(**expected) @@ -3563,8 +2689,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "scallop" + location = "abalone" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -3575,8 +2701,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "squid", + "location": "clam", } path = ConversationsClient.common_location_path(**expected) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_participants.py b/tests/unit/gapic/dialogflow_v2beta1/test_participants.py index 8887c027c..5e42b5752 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_participants.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_participants.py @@ -1707,11 +1707,6 @@ def test_analyze_content_flattened(): client.analyze_content( participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) @@ -1735,11 +1730,6 @@ def test_analyze_content_flattened_error(): gcd_participant.AnalyzeContentRequest(), participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) @@ -1761,11 +1751,6 @@ async def test_analyze_content_flattened_async(): response = await client.analyze_content( participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) @@ -1790,95 +1775,10 @@ async def test_analyze_content_flattened_error_async(): gcd_participant.AnalyzeContentRequest(), participant="participant_value", text_input=session.TextInput(text="text_value"), - audio_input=gcd_participant.AudioInput( - config=audio_config.InputAudioConfig( - audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 - ) - ), event_input=session.EventInput(name="name_value"), ) -def test_streaming_analyze_content( - transport: str = "grpc", request_type=participant.StreamingAnalyzeContentRequest -): - client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_analyze_content), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iter([participant.StreamingAnalyzeContentResponse()]) - - response = client.streaming_analyze_content(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - for message in response: - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -def test_streaming_analyze_content_from_dict(): - test_streaming_analyze_content(request_type=dict) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async( - transport: str = "grpc_asyncio", - request_type=participant.StreamingAnalyzeContentRequest, -): - client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - requests = [request] - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.streaming_analyze_content), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) - call.return_value.read = mock.AsyncMock( - side_effect=[participant.StreamingAnalyzeContentResponse()] - ) - - response = await client.streaming_analyze_content(iter(requests)) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert next(args[0]) == request - - # Establish that the response is the type that we expect. - message = await response.read() - assert isinstance(message, participant.StreamingAnalyzeContentResponse) - - -@pytest.mark.asyncio -async def test_streaming_analyze_content_async_from_dict(): - await test_streaming_analyze_content_async(request_type=dict) - - def test_suggest_articles( transport: str = "grpc", request_type=participant.SuggestArticlesRequest ): @@ -3094,7 +2994,6 @@ def test_participants_base_transport(): "list_participants", "update_participant", "analyze_content", - "streaming_analyze_content", "suggest_articles", "suggest_faq_answers", "suggest_smart_replies", From 9322e7adf5f57ae617b81eddc243e0950313c577 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Mon, 12 Apr 2021 19:34:17 +0000 Subject: [PATCH 5/5] chore: release 2.1.1 (#269) :robot: I have created a release \*beep\* \*boop\* --- ### [2.1.1](https://www.github.com/googleapis/python-dialogflow/compare/v2.1.0...v2.1.1) (2021-04-12) ### Bug Fixes * remove `input_audio` field from AnalyzeContentRequest from v2/v2beta1 ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) * remove proto message CreateCallMatcherRequest, CreateCallMatcherResponse, ListCallMatchersRequest, ListCallMatchersResponse, DeleteCallMatcherRequest, DeleteCallMatcherResponse, CallMatcher, StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse, AudioInput from v2/v2beta1, TelephonyDtmfEvents, TelephonyDtmf from v2 ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) * remove resource_reference for invisible resources ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) * Remove resource_reference from UpdateAnswerRecord ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) * remove rpc or fields that are unintended to release ([#264](https://www.github.com/googleapis/python-dialogflow/issues/264)) ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) * remove StreamingAnalyzeContent, CreateCallMatcher, ListCallMatchers, DeleteCallMatcher rpc from v2/v2beta1 ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) ### Documentation * **samples:** add Agent Assist code samples ([#267](https://www.github.com/googleapis/python-dialogflow/issues/267)) ([0a8cfb9](https://www.github.com/googleapis/python-dialogflow/commit/0a8cfb9ac71870df9f69ae518e32a920d08bd170)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 17 +++++++++++++++++ setup.py | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fd8fa6f6..6a763e7cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ [1]: https://pypi.org/project/dialogflow/#history +### [2.1.1](https://www.github.com/googleapis/python-dialogflow/compare/v2.1.0...v2.1.1) (2021-04-12) + + +### Bug Fixes + +* remove `input_audio` field from AnalyzeContentRequest from v2/v2beta1 ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) +* remove proto message CreateCallMatcherRequest, CreateCallMatcherResponse, ListCallMatchersRequest, ListCallMatchersResponse, DeleteCallMatcherRequest, DeleteCallMatcherResponse, CallMatcher, StreamingAnalyzeContentRequest, StreamingAnalyzeContentResponse, AudioInput from v2/v2beta1, TelephonyDtmfEvents, TelephonyDtmf from v2 ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) +* remove resource_reference for invisible resources ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) +* Remove resource_reference from UpdateAnswerRecord ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) +* remove rpc or fields that are unintended to release ([#264](https://www.github.com/googleapis/python-dialogflow/issues/264)) ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) +* remove StreamingAnalyzeContent, CreateCallMatcher, ListCallMatchers, DeleteCallMatcher rpc from v2/v2beta1 ([06381fc](https://www.github.com/googleapis/python-dialogflow/commit/06381fcc965669e1b3dc8bec22aa567dceb6f935)) + + +### Documentation + +* **samples:** add Agent Assist code samples ([#267](https://www.github.com/googleapis/python-dialogflow/issues/267)) ([0a8cfb9](https://www.github.com/googleapis/python-dialogflow/commit/0a8cfb9ac71870df9f69ae518e32a920d08bd170)) + ## [2.1.0](https://www.github.com/googleapis/python-dialogflow/compare/v2.0.0...v2.1.0) (2021-03-10) diff --git a/setup.py b/setup.py index 91e165a4d..f9006347a 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ name = "dialogflow" description = "Client library for the Dialogflow API" -version = "2.1.0" +version = "2.1.1" release_status = "Development Status :: 5 - Production/Stable" dependencies = ["google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.10.0"]