Skip to content

Commit 1342e16

Browse files
martini9393Ye Yuan
andauthored
feat: add sample code for using regional Dialogflow endpoint (#254)
* Add sample code for using regional dialogflow endpoint * Update comment * udpate some styles based on last round of reviews * run blacken to reformat files and update remaining string formatting Co-authored-by: Ye Yuan <[email protected]>
1 parent 64e2f27 commit 1342e16

21 files changed

+638
-429
lines changed

dialogflow/create_document_test.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222

2323
import document_management
2424

25-
PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT')
26-
KNOWLEDGE_BASE_NAME = 'knowledge_{}'.format(uuid.uuid4())
27-
DOCUMENT_DISPLAY_NAME = 'test_document_{}'.format(uuid.uuid4())
25+
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
26+
KNOWLEDGE_BASE_NAME = "knowledge_{}".format(uuid.uuid4())
27+
DOCUMENT_DISPLAY_NAME = "test_document_{}".format(uuid.uuid4())
2828
pytest.KNOWLEDGE_BASE_ID = None
2929

3030

@@ -33,17 +33,18 @@ def setup_teardown():
3333
# Create a knowledge base to use in document management
3434
client = dialogflow_v2beta1.KnowledgeBasesClient()
3535
project_path = client.common_project_path(PROJECT_ID)
36-
knowledge_base = dialogflow_v2beta1.KnowledgeBase(
37-
display_name=KNOWLEDGE_BASE_NAME)
38-
response = client.create_knowledge_base(parent=project_path, knowledge_base=knowledge_base)
39-
pytest.KNOWLEDGE_BASE_ID = response.name.split(
40-
'/knowledgeBases/')[1].split('\n')[0]
36+
knowledge_base = dialogflow_v2beta1.KnowledgeBase(display_name=KNOWLEDGE_BASE_NAME)
37+
response = client.create_knowledge_base(
38+
parent=project_path, knowledge_base=knowledge_base
39+
)
40+
pytest.KNOWLEDGE_BASE_ID = response.name.split("/knowledgeBases/")[1].split("\n")[0]
4141

4242
yield
4343

4444
# Delete the created knowledge base
4545
knowledge_base_path = client.knowledge_base_path(
46-
PROJECT_ID, pytest.KNOWLEDGE_BASE_ID)
46+
PROJECT_ID, pytest.KNOWLEDGE_BASE_ID
47+
)
4748
request = dialogflow_v2beta1.DeleteKnowledgeBaseRequest(
4849
name=knowledge_base_path, force=True
4950
)
@@ -53,7 +54,12 @@ def setup_teardown():
5354
@pytest.mark.flaky(max_runs=3, min_passes=1)
5455
def test_create_document(capsys):
5556
document_management.create_document(
56-
PROJECT_ID, pytest.KNOWLEDGE_BASE_ID, DOCUMENT_DISPLAY_NAME,
57-
'text/html', 'FAQ', 'https://cloud.google.com/storage/docs/faq')
57+
PROJECT_ID,
58+
pytest.KNOWLEDGE_BASE_ID,
59+
DOCUMENT_DISPLAY_NAME,
60+
"text/html",
61+
"FAQ",
62+
"https://cloud.google.com/storage/docs/faq",
63+
)
5864
out, _ = capsys.readouterr()
5965
assert DOCUMENT_DISPLAY_NAME in out

dialogflow/create_knowledge_base_test.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222

2323
import knowledge_base_management
2424

25-
PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT')
26-
KNOWLEDGE_BASE_NAME = 'knowledge_{}'.format(uuid.uuid4())
25+
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
26+
KNOWLEDGE_BASE_NAME = "knowledge_{}".format(uuid.uuid4())
2727
pytest.KNOWLEDGE_BASE_ID = None
2828

2929

@@ -35,14 +35,14 @@ def teardown():
3535
client = dialogflow_v2beta1.KnowledgeBasesClient()
3636
assert pytest.KNOWLEDGE_BASE_ID is not None
3737
knowledge_base_path = client.knowledge_base_path(
38-
PROJECT_ID, pytest.KNOWLEDGE_BASE_ID)
38+
PROJECT_ID, pytest.KNOWLEDGE_BASE_ID
39+
)
3940
client.delete_knowledge_base(name=knowledge_base_path)
4041

4142

4243
def test_create_knowledge_base(capsys):
43-
knowledge_base_management.create_knowledge_base(PROJECT_ID,
44-
KNOWLEDGE_BASE_NAME)
44+
knowledge_base_management.create_knowledge_base(PROJECT_ID, KNOWLEDGE_BASE_NAME)
4545
out, _ = capsys.readouterr()
4646
assert KNOWLEDGE_BASE_NAME in out
4747

48-
pytest.KNOWLEDGE_BASE_ID = out.split('/knowledgeBases/')[1].split('\n')[0]
48+
pytest.KNOWLEDGE_BASE_ID = out.split("/knowledgeBases/")[1].split("\n")[0]

dialogflow/detect_intent_audio.py

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@
3131

3232

3333
# [START dialogflow_detect_intent_audio]
34-
def detect_intent_audio(project_id, session_id, audio_file_path,
35-
language_code):
34+
def detect_intent_audio(project_id, session_id, audio_file_path, language_code):
3635
"""Returns the result of detect intent with an audio file as input.
3736
3837
Using the same `session_id` between requests allows continuation
@@ -46,14 +45,16 @@ def detect_intent_audio(project_id, session_id, audio_file_path,
4645
sample_rate_hertz = 16000
4746

4847
session = session_client.session_path(project_id, session_id)
49-
print('Session path: {}\n'.format(session))
48+
print("Session path: {}\n".format(session))
5049

51-
with open(audio_file_path, 'rb') as audio_file:
50+
with open(audio_file_path, "rb") as audio_file:
5251
input_audio = audio_file.read()
5352

5453
audio_config = dialogflow.InputAudioConfig(
55-
audio_encoding=audio_encoding, language_code=language_code,
56-
sample_rate_hertz=sample_rate_hertz)
54+
audio_encoding=audio_encoding,
55+
language_code=language_code,
56+
sample_rate_hertz=sample_rate_hertz,
57+
)
5758
query_input = dialogflow.QueryInput(audio_config=audio_config)
5859

5960
request = dialogflow.DetectIntentRequest(
@@ -63,40 +64,43 @@ def detect_intent_audio(project_id, session_id, audio_file_path,
6364
)
6465
response = session_client.detect_intent(request=request)
6566

66-
print('=' * 20)
67-
print('Query text: {}'.format(response.query_result.query_text))
68-
print('Detected intent: {} (confidence: {})\n'.format(
69-
response.query_result.intent.display_name,
70-
response.query_result.intent_detection_confidence))
71-
print('Fulfillment text: {}\n'.format(
72-
response.query_result.fulfillment_text))
67+
print("=" * 20)
68+
print("Query text: {}".format(response.query_result.query_text))
69+
print(
70+
"Detected intent: {} (confidence: {})\n".format(
71+
response.query_result.intent.display_name,
72+
response.query_result.intent_detection_confidence,
73+
)
74+
)
75+
print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
76+
77+
7378
# [END dialogflow_detect_intent_audio]
7479

7580

76-
if __name__ == '__main__':
81+
if __name__ == "__main__":
7782
parser = argparse.ArgumentParser(
78-
description=__doc__,
79-
formatter_class=argparse.RawDescriptionHelpFormatter)
83+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
84+
)
8085
parser.add_argument(
81-
'--project-id',
82-
help='Project/agent id. Required.',
83-
required=True)
86+
"--project-id", help="Project/agent id. Required.", required=True
87+
)
8488
parser.add_argument(
85-
'--session-id',
86-
help='Identifier of the DetectIntent session. '
87-
'Defaults to a random UUID.',
88-
default=str(uuid.uuid4()))
89+
"--session-id",
90+
help="Identifier of the DetectIntent session. " "Defaults to a random UUID.",
91+
default=str(uuid.uuid4()),
92+
)
8993
parser.add_argument(
90-
'--language-code',
94+
"--language-code",
9195
help='Language code of the query. Defaults to "en-US".',
92-
default='en-US')
96+
default="en-US",
97+
)
9398
parser.add_argument(
94-
'--audio-file-path',
95-
help='Path to the audio file.',
96-
required=True)
99+
"--audio-file-path", help="Path to the audio file.", required=True
100+
)
97101

98102
args = parser.parse_args()
99103

100104
detect_intent_audio(
101-
args.project_id, args.session_id, args.audio_file_path,
102-
args.language_code)
105+
args.project_id, args.session_id, args.audio_file_path, args.language_code
106+
)

dialogflow/detect_intent_audio_test.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,18 @@
1919
from detect_intent_audio import detect_intent_audio
2020

2121
DIRNAME = os.path.realpath(os.path.dirname(__file__))
22-
PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT')
23-
SESSION_ID = 'test_{}'.format(uuid.uuid4())
22+
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
23+
SESSION_ID = "test_{}".format(uuid.uuid4())
2424
AUDIOS = [
25-
'{0}/resources/book_a_room.wav'.format(DIRNAME),
26-
'{0}/resources/mountain_view.wav'.format(DIRNAME),
27-
'{0}/resources/today.wav'.format(DIRNAME),
25+
"{0}/resources/book_a_room.wav".format(DIRNAME),
26+
"{0}/resources/mountain_view.wav".format(DIRNAME),
27+
"{0}/resources/today.wav".format(DIRNAME),
2828
]
2929

3030

3131
def test_detect_intent_audio(capsys):
3232
for audio_file_path in AUDIOS:
33-
detect_intent_audio(PROJECT_ID, SESSION_ID, audio_file_path, 'en-US')
33+
detect_intent_audio(PROJECT_ID, SESSION_ID, audio_file_path, "en-US")
3434
out, _ = capsys.readouterr()
3535

36-
assert 'Fulfillment text: What time will the meeting start?' in out
36+
assert "Fulfillment text: What time will the meeting start?" in out

dialogflow/detect_intent_knowledge.py

Lines changed: 50 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@
2828

2929

3030
# [START dialogflow_detect_intent_knowledge]
31-
def detect_intent_knowledge(project_id, session_id, language_code,
32-
knowledge_base_id, texts):
31+
def detect_intent_knowledge(
32+
project_id, session_id, language_code, knowledge_base_id, texts
33+
):
3334
"""Returns the result of detect intent with querying Knowledge Connector.
3435
3536
Args:
@@ -41,69 +42,79 @@ def detect_intent_knowledge(project_id, session_id, language_code,
4142
texts: A list of text queries to send.
4243
"""
4344
from google.cloud import dialogflow_v2beta1 as dialogflow
45+
4446
session_client = dialogflow.SessionsClient()
4547

4648
session_path = session_client.session_path(project_id, session_id)
47-
print('Session path: {}\n'.format(session_path))
49+
print("Session path: {}\n".format(session_path))
4850

4951
for text in texts:
50-
text_input = dialogflow.TextInput(
51-
text=text, language_code=language_code)
52+
text_input = dialogflow.TextInput(text=text, language_code=language_code)
5253

5354
query_input = dialogflow.QueryInput(text=text_input)
5455

55-
knowledge_base_path = dialogflow.KnowledgeBasesClient \
56-
.knowledge_base_path(project_id, knowledge_base_id)
56+
knowledge_base_path = dialogflow.KnowledgeBasesClient.knowledge_base_path(
57+
project_id, knowledge_base_id
58+
)
5759

5860
query_params = dialogflow.QueryParameters(
59-
knowledge_base_names=[knowledge_base_path])
61+
knowledge_base_names=[knowledge_base_path]
62+
)
6063

6164
request = dialogflow.DetectIntentRequest(
62-
session=session_path,
63-
query_input=query_input,
64-
query_params=query_params
65+
session=session_path, query_input=query_input, query_params=query_params
6566
)
6667
response = session_client.detect_intent(request=request)
6768

68-
print('=' * 20)
69-
print('Query text: {}'.format(response.query_result.query_text))
70-
print('Detected intent: {} (confidence: {})\n'.format(
71-
response.query_result.intent.display_name,
72-
response.query_result.intent_detection_confidence))
73-
print('Fulfillment text: {}\n'.format(
74-
response.query_result.fulfillment_text))
75-
print('Knowledge results:')
69+
print("=" * 20)
70+
print("Query text: {}".format(response.query_result.query_text))
71+
print(
72+
"Detected intent: {} (confidence: {})\n".format(
73+
response.query_result.intent.display_name,
74+
response.query_result.intent_detection_confidence,
75+
)
76+
)
77+
print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
78+
print("Knowledge results:")
7679
knowledge_answers = response.query_result.knowledge_answers
7780
for answers in knowledge_answers.answers:
78-
print(' - Answer: {}'.format(answers.answer))
79-
print(' - Confidence: {}'.format(
80-
answers.match_confidence))
81+
print(" - Answer: {}".format(answers.answer))
82+
print(" - Confidence: {}".format(answers.match_confidence))
83+
84+
8185
# [END dialogflow_detect_intent_knowledge]
8286

8387

84-
if __name__ == '__main__':
88+
if __name__ == "__main__":
8589
parser = argparse.ArgumentParser(
86-
description=__doc__,
87-
formatter_class=argparse.RawDescriptionHelpFormatter)
90+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
91+
)
8892
parser.add_argument(
89-
'--project-id', help='Project/agent id. Required.', required=True)
93+
"--project-id", help="Project/agent id. Required.", required=True
94+
)
9095
parser.add_argument(
91-
'--session-id',
92-
help='ID of the DetectIntent session. '
93-
'Defaults to a random UUID.',
94-
default=str(uuid.uuid4()))
96+
"--session-id",
97+
help="ID of the DetectIntent session. " "Defaults to a random UUID.",
98+
default=str(uuid.uuid4()),
99+
)
95100
parser.add_argument(
96-
'--language-code',
101+
"--language-code",
97102
help='Language code of the query. Defaults to "en-US".',
98-
default='en-US')
103+
default="en-US",
104+
)
99105
parser.add_argument(
100-
'--knowledge-base-id',
101-
help='The id of the Knowledge Base to query against',
102-
required=True)
103-
parser.add_argument('texts', nargs='+', type=str, help='Text inputs.')
106+
"--knowledge-base-id",
107+
help="The id of the Knowledge Base to query against",
108+
required=True,
109+
)
110+
parser.add_argument("texts", nargs="+", type=str, help="Text inputs.")
104111

105112
args = parser.parse_args()
106113

107-
detect_intent_knowledge(args.project_id, args.session_id,
108-
args.language_code, args.knowledge_base_id,
109-
args.texts)
114+
detect_intent_knowledge(
115+
args.project_id,
116+
args.session_id,
117+
args.language_code,
118+
args.knowledge_base_id,
119+
args.texts,
120+
)

dialogflow/detect_intent_knowledge_test.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,16 @@
1919

2020
import detect_intent_knowledge
2121

22-
PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT')
23-
SESSION_ID = 'session_{}'.format(uuid.uuid4())
24-
KNOWLEDGE_BASE_ID = 'MjEwMjE4MDQ3MDQwMDc0NTQ3Mg'
25-
TEXTS = ['Where is my data stored?']
22+
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
23+
SESSION_ID = "session_{}".format(uuid.uuid4())
24+
KNOWLEDGE_BASE_ID = "MjEwMjE4MDQ3MDQwMDc0NTQ3Mg"
25+
TEXTS = ["Where is my data stored?"]
2626

2727

2828
def test_detect_intent_knowledge(capsys):
2929
detect_intent_knowledge.detect_intent_knowledge(
30-
PROJECT_ID, SESSION_ID, 'en-us', KNOWLEDGE_BASE_ID, TEXTS)
30+
PROJECT_ID, SESSION_ID, "en-us", KNOWLEDGE_BASE_ID, TEXTS
31+
)
3132

3233
out, _ = capsys.readouterr()
33-
assert 'Knowledge results' in out
34+
assert "Knowledge results" in out

0 commit comments

Comments
 (0)