The story of embedding Dialogflow in a Java application

Introduction

I created a Java application that incorporates Dialogflow, so The procedure is briefly summarized as a memorandum. When actually using it, I think that you will write the one described here + Swing etc.

Reference material

Development environment

What you need

What is Dialogflow?

Dialogflow is a natural language understanding platform that facilitates the design of conversational user interfaces and integration into mobile apps, web applications, devices, bots, interactive voice response systems, and more. Source: Official Documents

It is used for natural language analysis of Google Home, and is used for AWS [Amazon Lex](https://aws.amazon.com/jp/lex/'https://aws.amazon.com/jp Similar systems include / lex /').


1. GCP project-Creation of Dialogflow interaction model

1.1. Creating a Google Cloud Platform (GCP) project

Create a GCP project to connect Dialogflow.

1.2. Dialogflow Creating a dialogue model

Now let's create a Dialogflow interaction model. For information on creating an interaction model, see the Official Documentation (https://cloud.google.com/dialogflow/docs/quick/build-agent'https://cloud.google.com/dialogflow/docs/quick/build) -agent') and others There is a lot of information on the net, so I will omit it.

This time, it returns "Hello Dialogflow!" To the utterance "test". I have created a test interaction model.

1.3. Download json file for authentication


2. Incorporate Dialogflow into your Java application

2.1. Create maven project

2.2. Creating a package class file

Create packages and class files in the created Maven project.

You have now created a package and a class with the main methods in your Maven project.

2.3. Editing pom.xml

Rewrite the file called pom.xml in the created Maven project as follows.

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <!--groupId and artifactId...Replace with the one you entered when you created the Maven project.-->
  <modelVersion>4.0.0</modelVersion>
  <groupId>...</groupId>
  <artifactId>...</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>
  
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.2</version>
        <configuration>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>
      
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <finalName>...</finalName>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <!--of mainClass...Is the package name.The class name.-->
              <mainClass>...</mainClass>
            </manifest>
          </archive>
        </configuration>
        <executions>
          <execution>
            <id>mark-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>libraries-bom</artifactId>
        <version>5.1.0</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-dialogflow</artifactId>
    </dependency>
  </dependencies>
</project>

When you're done, save and apply pom.xml.

UpdateMavenProject.gif

2.4. Editing Java files

Rewrite the class file containing the main method created earlier as follows.

Main.java


//Replace the package name as appropriate.
package tokyo.penguin_syan.dialogflowTest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.google.api.client.util.Maps;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.TextInput.Builder;

public class Main {

  public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    List<String> text = new ArrayList<String>();
    String input;
    Map<String, QueryResult> ret;
    //sessionId is a suitable number for testing.
    int sessionId = 123456789;

    do {
      System.out.print("\nYou  : ");
      input = userInput.next();
      if(input.equals("exit"))
        System.exit(0);

      text.add(input);
      ret = new HashMap<>();

      try {
        //In the argument---Is the project described in the downloaded json file_Please replace with id.
        ret.putAll(detectIntentTexts(---,
            text, String.valueOf(sessionId++), "ja"));
        System.out.format("Agent: %s\n", ret.get(input).getFulfillmentText());
      } catch (Exception e) {
        e.printStackTrace();
      }

    }while(true);
  }

  public static Map<String, QueryResult> detectIntentTexts(
    String projectId,
    List<String> texts,
    String sessionId,
    String languageCode) throws Exception {
      Map<String, QueryResult> queryResults = Maps.newHashMap();
      try (SessionsClient sessionsClient = SessionsClient.create()) {
        SessionName session = SessionName.of(projectId, sessionId);
        for (String text : texts) {
          Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
          QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
          DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
          QueryResult queryResult = response.getQueryResult();
          queryResults.put(text, queryResult);
        }
      }
    return queryResults;
  }

}

2.5. Compile


3. Run

3.1. Creating a bat file for execution

Create a bat file for execution.

dialogflowTest_java.bat


@echo off

rem ---Enter the name of the downloaded json file for authentication.
set GOOGLE_APPLICATION_CREDENTIALS=---.json
java -jar test-jar-with-dependencies.jar

Organize the directory structure for execution.

Directory structure


.
├ test-jar-with-dependencies.jar
├ ---.json
└ dialogflowTest_java.bat

3.2. Execution

To execute it, start the created bat file. run.gif

I was able to execute it safely. ٩ (๑ • ㅂ •) ۶ Wow

Recommended Posts

The story of embedding Dialogflow in a Java application
The story of writing Java in Emacs
Let's create a TODO application in Java 5 Switch the display of TODO
The story of low-level string comparison in Java
The story of making ordinary Othello in Java
A story about the JDK in the Java 11 era
The story of learning Java in the first programming
Measure the size of a folder in Java
The story of forgetting to close a file in Java and failing
[Java version] The story of serialization
Story of making a task management application with swing, java
A quick explanation of the five types of static in Java
Let's make a calculator application in Java ~ Display the application window
Get the result of POST in Java
Let's create a TODO application in Java 4 Implementation of posting function
Let's create a TODO application in Java 6 Implementation of search function
Let's create a TODO application in Java 8 Implementation of editing function
A story about hitting the League Of Legends API with JAVA
Get the public URL of a private Flickr file in Java
Let's create a TODO application in Java 1 Brief explanation of MVC
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
The story of making a game launcher with automatic loading function [Java]
The story of acquiring Java Silver in two months from completely inexperienced.
Sample program that returns the hash value of a file in Java
How to get the absolute path of a directory running in Java
The story that the Servlet could not be loaded in the Java Web application
[Java] Handling of JavaBeans in the method chain
About the idea of anonymous classes in Java
Feel the passage of time even in Java
A quick review of Java learned in class
I received the data of the journey (diary application) in Java and visualized it # 001
Let's make a calculator application with Java ~ Create a display area in the window
A story confirming the implementation of the SendGrid Java library when mail delivery fails
Validate the identity token of a user authenticated with AWS Cognito in Java
Get the URL of the HTTP redirect destination in Java
A quick review of Java learned in class part4
The story of making a reverse proxy with ProxyServlet
The story of an Illegal State Exception in Jetty.
A note for Initializing Fields in the Java tutorial
[Java] Get the file in the jar regardless of the environment
[Java] When writing the source ... A memorandum of understanding ①
A quick review of Java learned in class part3
A quick review of Java learned in class part2
Change the storage quality of JPEG images in Java
The story of making dto, dao-like with java, sqlite
Summarize the additional elements of the Optional class in Java 9
The story that .java is also built in Unity 2018
[Java] Integer information of characters in a text file acquired by the read () method
Write a test by implementing the story of Mr. Nabeats in the world with ruby
Find a subset in Java
Was done in the base year of the Java calendar week
Check the dependency of a specific maven artifact in Coursier
20190803_Java & k8s on Azure The story of going to the festival
A story packed with the basics of Spring Boot (solved)
Check the operation of two roles with a chat application
The story of throwing BLOB data from EXCEL in DBUnit
Check the status of Java application without using monitoring tool
Activate Excel file A1 cell of each sheet in Java
Create a method to return the tax rate in Java
Set the time zone in the JVM of your Azure application
Count the number of digits after the decimal point in Java