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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Integration Patterns in Microservices World
  • Building an Angular Bot With AWS Lex
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together

Trending

  • Implementing the Planning Pattern With Java Enterprise and LangChain4j
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial
  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
16.1K 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

  • How To Build Web Service Using Spring Boot 2.x
  • Integration Patterns in Microservices World
  • Building an Angular Bot With AWS Lex
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook