Working with Dialogflow using Python Client

Sachin PC
The Startup
Published in
6 min readOct 11, 2019

If you are reading this article you probably know what a conversational agent is and why they have become a significant part of our day-to-day lives. For those who think they are not familiar with such systems, I am talking about the Google Assistant, Siri, Cortana, etc. (C’mon, don’t tell me you haven’t heard about at least one of these.) So, I am going to say it upfront, this article is for those who want to interface with a Dialogflow agent using Python rather than using their default GUI.

Goal of this article: Help you pass an utterance to the Dialogflow agent from a Python client and retrieve the intent and the confidence.

And now it is time to get our hands dirty.

Step 1: Create an agent in Dialogflow.

When you sign in to your Dialogflow account and go to your console, you should be able to see this page (Fig 1).

Fig 1

Click the Create Agent button and you should be seeing a page like this (Fig 2). I’m going to go ahead and fill in the following details on this page.

Fig 2
  1. Agent Name: TestBot
  2. Default Language: English-en
  3. Default Time Zone: Choose you time zone, I chose (GMT+10:00) Australia/Sydney.
  4. Google Project: Let it hold the default value. To keep things simple, let us not change it.

And then click CREATE. It will take a minute or two to set things up for you.

Once the agent is ready, you will be taken to a page that looks like this (Fig 3).

Fig 3

I have split the screen into 3 zones.

Zone 1: Dialogflow Test Console

Zone 2: I call it the Dialogflow Command Center :P

Zone 3: Main Panel

You have officially built your first chatbot and now it is time to take it for a test ride.

In the test console, let us type in a simple “Hello” and hit the Enter key.

Fig 4: The highlighted zones show the input message, the response from the chatbot and the identified intention of the user’s utterance.

In Fig 4, the Intent identified for the airport is “Default Welcome Intent”. Now let us try the same using a Python Client.

I will be using PyCharm Professional Edition as it is one of my favorite IDE, but feel free to use whichever you are comfortable with. Below what you see is the code for Python client that sends an utterance and retrieves the name of the intent, the confidence, and fulfillment text.

"""Install the following requirements:
dialogflow 0.5.1
google-api-core 1.4.1
"""
import
os
import dialogflow
from google.api_core.exceptions import InvalidArgument

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'private_key.json'

DIALOGFLOW_PROJECT_ID = '[PROJECT_ID]'
DIALOGFLOW_LANGUAGE_CODE = '[LANGUAGE]
SESSION_ID = 'me'

text_to_be_analyzed = "Howdy"

session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except
InvalidArgument:
raise

print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)

In the code above, the following variables need to be initialized:

  1. DIALOGFLOW_PROJECT_ID
  2. DIALOGFLOW_LANGUAGE_CODE

Let’s find out these values from our Dialogflow agent setting. Click the gear icon highlighted in Fig 5 below and it will take you to the agent settings page:

Fig 5: The highlighted gear icon gives you the configuration of the dialogflow agents.
Fig 6: Settings page of the agent

In Fig 6, Zone 1 is the project ID that needs to be assigned to DIALOGFLOW_PROJECT_ID and Zone 2 is the Language that needs to be assigned to DIALOGFLOW_LANGUAGE_CODE. Hence the code becomes as below:

"""Install the following requirements:
dialogflow 0.5.1
google-api-core 1.4.1
"""
import
os
import dialogflow
from google.api_core.exceptions import InvalidArgument

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'private_key.json'

DIALOGFLOW_PROJECT_ID = 'xxxxxxxxxxxxxx'
DIALOGFLOW_LANGUAGE_CODE = 'en'
SESSION_ID = 'me'

text_to_be_analyzed = "Howdy"

session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except
InvalidArgument:
raise

print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)

You might be wondering what the private_key.json is. Don’t sweat it. The next section will take you through the steps to get the private key file.

Open a new tab on your browser and go to your google cloud console to ensure that API services for Dialogflow are enabled as shown in Fig 7.

Fig 7: Ensure the Dialogflow API service is enabled.

Once it is verified, go back to the agent settings page by clicking the gear icon and you should be seeing the page in Fig 8 like the last time we did this.

Fig 8: Dialogflow agent settings page

But this time, we will click on the link provided in Zone 1 which will take you to the service account page that looks like Fig 9.

Fig 9: Service Account page

In Fig 9, click the “+ CREATE KEY” button and you shall see the following prompt open up (Fig 10).

Fig 10: Choose JSON as key type and then Create

Once the private key is generated a message should be displayed as follows:

Fig 11: Message prompt once private key is generated.

You will see a file with your project name downloading once this is happening. If your project name is xyz, the file that gets downloaded would be xyz.json. Rename this file to private_key.json and place it along with the python file that you created using the code provided below:

"""Install the following requirements:
dialogflow 0.5.1
google-api-core 1.4.1
"""
import
os
import dialogflow
from google.api_core.exceptions import InvalidArgument

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'private_key.json'

DIALOGFLOW_PROJECT_ID = 'xxxxxxxxxxxxxx'
DIALOGFLOW_LANGUAGE_CODE = 'en'
SESSION_ID = 'me'

text_to_be_analyzed = "Howdy"

session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except
InvalidArgument:
raise

print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)

And now you are officially ready to run your Dialogflow Python Client.

If you are new to the Google Cloud Platform(GCP), it might a little confusing as to what a Service Account is and why you had to download a private key. I would suggest you go through the following links to understand GCP and its components better.

  1. https://cloud.google.com/iam/docs/service-accounts
  2. https://dialogflow.com/docs/reference/v2-auth-setup

Now, for the final step. Run the Python code and you should see the following output:

Fig 12: Output after running the python code.

The most important tip while working with Dialogflow — Feel free to contact Dialogflow support any time you are stuck with anything, they are very prompt and try to answer your questions with as many details as possible.

I will be back with more articles on playing around with Dialogflow and Python. Until then……feel free to connect with me:

Email: sachinpc.1993@live.com

LinkedIn: https://www.linkedin.com/in/sachinpc/

--

--

Sachin PC
The Startup

Data Scientist | PhD Student in Computer Science