{{announcement.body}}
{{announcement.title}}

Build Chatbots with Dialogflow - Step By Step Guidelines

DZone 's Guide to

Build Chatbots with Dialogflow - Step By Step Guidelines

This tutorial provides a detailed guide of how to set up create tracks and integrations for chatbots with Google's Dialogflow Agent application.

· AI Zone ·
Free Resource

Dialogflow from Google (earlier known as API.ai) is a great platform for developing chatbots for multiple platforms. Earlier when Dialogflow was known as API.ai, they had an Android and iOS client library to integrate chatbot into mobile apps. But after merging into Google, the existing library is not getting updated; rather we are seeing Dialogflow added to Google’s Cloud platform and a new Java-based client API is being developed.

Dialogflow

In this article, I will show you how you can integrate a chatbot developed in Dialogflow using the new Java client API. 

1. First, we will create a Dialogflow Agent which we will name FirstActionApp.

Please click on this link.


FirstActionApp

FirstActionApp



Note: Dialogflow V1 API will be shut down on March 31st, 2020.

So we are creating a Dialogflow app with V2 API version. The service account in this image is used for creating credentials for the Java client API.

V2 API

V2 API


For creating a chatbot with V1 API we use the client access token which is used for integrating the Android client library. For creating a chatbot with V2 API we have to go with a service account.

  • Select your App.

Select application

Select application
  • Create a new key with Dialogflow integrations and download the created JSON file.

2. Now we will create the Intents and Entities to train the agent.

Intents

Intents


Tracks

Tracks


  • Adding synonyms to capture track values.

Adding tracks

Adding tracks



Create parameter to fetch track

Create parameter to fetch track


  • Create a parameter to fetch the track.

Create responses

Create responses


Add responses

Add responses


  • Enable webhook calls are deployed code through web service to provide data to the user.

Add webhooks

Add webhooks


By default, your agent responds to a matched intent with a static response. If you're using one of the integrations options, you can provide a more dynamic response by using fulfillment. When you enable fulfillment for an intent, Dialogflow responds to that intent by calling a service that you define. For example, if an end-user wants to schedule a haircut on Friday, your service can check your database and respond to the end-user with availability information for Friday.

  1. The end-user types or speaks an expression.

  2. Dialogflow matches the end-user expression to an intent and extracts parameters.

  3. Dialogflow sends a webhook request message to your webhook service. This message contains information about the matched intent, the action, the parameters, and the response defined for the intent.

  4. Your service performs actions as needed, like database queries or external API calls.

  5. Your service sends a webhook response  message to Dialog Flow. This message contains the response that should be sent to the end-user.

  6. Dialogflow sends the response to the end-user.

  7. The end-user sees or hears the response.

3. Create a cloud function fulfillment to handle the webhook request. Based on the detected track number, an appropriate response will be send to the user.


Cloud function fulfillment

Cloud function fulfillment



The Dialogflow Console has a built-in code editor, called the inline editor, that you can use to create fulfillment code and deploy the code to Clout functions for Firebase. The inline editor is intended for simple fulfillment testing and prototyping. Once you are ready to build a production application, you should create a webhook service.

4. Now our Agent is ready and we will now integrate it to the Android app. In the build.gradle(app), we will add the dependencies for both Android client library and Java client API as we will be developing for both.

Java
 




xxxxxxxxxx
1


 
1
// Java V2
2
 
          
3
implementation 'com.google.cloud:google-cloud-dialogflow:0.67.0-alpha'


5. The chatbot will be initiated in the onCreate method of the Android activity. We will first configure the Dialog Flow agent using either the Client Access Token or using the JSON key. Then a new session is created using the unique ID and then the bot is made ready to communicate with the user.

  • Client access token can not be used because that was used by V1 API.

  • We are using V2 so, we will use the JSON key.

Java
 




x
27


 
1
private void initV2Chatbot() {
2
   try {
3
       InputStream stream = getResources().openRawResource(R.raw.test_agent_credentials);
4
       GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
5
       String projectId = ((ServiceAccountCredentials)credentials).getProjectId();
6
       SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
7
       SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
8
       sessionsClient = SessionsClient.create(sessionsSettings);
9
       session = SessionName.of(projectId, uuid);
10
   } catch (Exception e) {
11
       e.printStackTrace();
12
   }
13
}


  • The  test_agent_credentials  is the JSON file which we downloaded in the first step from the Service account.

  • We have copy and paste that file in the directory app -> res -> raw(new directory) and Paste.

6. We will handle the communication with the chatbot in an Asynchronous way. This we will do in  AsyncTask where the request query from the user is send as a request to the chatbot and the response is captured.

Java
 




xxxxxxxxxx
1
30


 
1
public class RequestJavaV2Task extends AsyncTask<Void, Void, DetectIntentResponse>
2
 Activity activity;
3
   private SessionName session;
4
   private SessionsClient sessionsClient;
5
   private QueryInput queryInput;
6
   RequestJavaV2Task(Activity activity, SessionName session, SessionsClient sessionsClient, QueryInput queryInput) {
7
       this.activity = activity;
8
       this.session = session;
9
       this.sessionsClient = sessionsClient;
10
       this.queryInput = queryInput;
11
   }
12
   @Override
13
   protected DetectIntentResponse doInBackground(Void... voids) {
14
       try{
15
           DetectIntentRequest detectIntentRequest =
16
                   DetectIntentRequest.newBuilder()
17
                           .setSession(session.toString())
18
                           .setQueryInput(queryInput)
19
                           .build();
20
           return sessionsClient.detectIntent(detectIntentRequest);
21
       } catch (Exception e) {
22
           e.printStackTrace();
23
       }
24
       return null;
25
   }
26
 
          
27
   @Override
28
   protected void onPostExecute(DetectIntentResponse response) {
29
       ((MainActivity) activity).callbackV2(response);
30
   }
31
}



7. The user can send a query from the Android app using EditText and the response will be shown in a TextView.

Java
 




xxxxxxxxxx
1
27


 
1
private void sendMessage(View view) {
2
       String msg = queryEditText.getText().toString();
3
       if (msg.trim().isEmpty()) {
4
           Toast.makeText(MainActivity.this, "Please enter your query!", Toast.LENGTH_LONG).show();
5
       } else {
6
           showTextView(msg, USER);
7
           queryEditText.setText("");
8
       
9
           // Java V2
10
           QueryInput queryInput = QueryInput.newBuilder().setText(TextInput.newBuilder().setText(msg).setLanguageCode("en-US")).build();
11
           new RequestJavaV2Task(MainActivity.this, session, sessionsClient, queryInput).execute();
12
       }
13
  }


Get Response:

Java
 




xxxxxxxxxx
1
17
9


 
1
public void callbackV2(DetectIntentResponse response) {
2
   if (response != null) {
3
       // process aiResponse here
4
       String botReply = response.getQueryResult().getFulfillmentText();
5
        showTextView(botReply, BOT);
6
   } else {
7
        showTextView("There was some communication issue. Please Try again!", BOT);
8
   }
9
}



Topics:
ai ,android ,appdev ,application ,chat bots ,chatbot ,dialogflow ,dialogflow tutorial ,google ,ios

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}