DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • 6 of the Best API Testing Tools in the Market
  • How To Build Web Service Using Spring Boot 2.x
  • Integration Patterns in Microservices World
  • Building an Angular Bot With AWS Lex

Trending

  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Monolith: The Good, The Bad and The Ugly
  • Event-Driven Microservices: How Kafka and RabbitMQ Power Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  1. DZone
  2. Data Engineering
  3. Databases
  4. Build Chatbots with Dialogflow - Step By Step Guidelines

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.

By 
Rahul Panchal user avatar
Rahul Panchal
·
Mar. 18, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
15.6K Views

Join the DZone community and get the full member experience.

Join For Free

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
}



Dialogflow Chatbot End user Web Service API mobile app Build (game engine) Database Java (programming language) Intent (military)

Opinions expressed by DZone contributors are their own.

Related

  • 6 of the Best API Testing Tools in the Market
  • How To Build Web Service Using Spring Boot 2.x
  • Integration Patterns in Microservices World
  • Building an Angular Bot With AWS Lex

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!