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

Implementing a Web Chat With AI in Java

DZone 's Guide to

Implementing a Web Chat With AI in Java

This article shows step by step how to implement a web chatbot using Java. Go through the steps of creating a new project and seeing the results!

· Java Zone ·
Free Resource

This article shows step by step how to implement a web chatbot using Java.

Creating a New Project

Start by generating a new Maven project:

  1. Go to https://start.vaadin.com.
  2. Delete all the default views (Dashboard and Master-Detail).
  3. Add a new view by clicking on the plus icon and select Empty.
  4. Change the name to Chat and the route to chat.
  5. Optional: Tweak the theme using the options on the right side of the page.
  6. Click Download app and set a Project Name, Java Group ID, and Vaadin Version (this article uses 14 LTS).
  7. Click Download, unzip the generated file, and import the Maven project into your favorite IDE (see instructions for IntelliJ IDEA, Eclipse, and NetBeans).
  8. Remove the  backend  subpackage and its contents.

Adding the Required Dependencies

You'll need an AIML library and the avataaar component by Artur Signell. To add them:

  1. Open the  pom.xml  file in your IDE.
  2. Add the following to the  <repositories>  section:
XML
 




x


 
1
<repository>
2
    <id>JCenter</id>
3
    <url>https://jcenter.bintray.com</url>
4
</repository>


  1. Add the following to the  <dependencies>  section:

Java
 




x
4
11


1
<dependency>
2
    <groupId>org.goldrenard</groupId>
3
    <artifactId>ab</artifactId>
4
    <version>1.0.7</version>
5
</dependency>
6
<dependency>
7
    <groupId>org.vaadin.artur</groupId>
8
    <artifactId>avataaar</artifactId>
9
    <version>1.0.0</version>
10
</dependency>


Implementing the Bot Logic

The bot logic is defined with Artificial Intelligence Markup Language (AIML). The  org.alicebot.ab.Bot  class allows you to generate intelligent-looking answers. You only need to add the AIML files and define a Spring-managed bean to access the bot logic.

Adding Ready-Made AIML Files

The set of rules that make up the AI the chatbot uses is defined in AIML files. You can create your own or download ready-to-use files. This article uses the free A.L.I.C.E. AIML files by Richard Wallace.

To add the A.L.I.C.E. AIML to your project:

  1. Go to https://github.com/drwallace/aiml-en-us-foundation-alice.
  2. Download the repository as a zip file.
  3. Extract the zip file and copy the contents (only the  .aiml  files) to a new  src/resources/bots/alice/aiml/  directory inside your Maven project (you have to create the  bots/alice/aiml/  subdirectory).

Defining the Bean to Access the Bot Logic

To implement the bot logic:

  1. Open the  Application  class in your IDE.

  2. Add the following methods:

Java
 




xxxxxxxxxx
1
14


 
1
@Bean
2
public Bot alice() {
3
    return new Bot(BotConfiguration.builder()
4
            .name("alice")
5
            .path("src/main/resources")
6
            .build()
7
    );
8
}
9
 
          
10
@Bean
11
public ScheduledExecutorService executorService() {
12
    return Executors.newScheduledThreadPool(2);
13
}



  1. Add the following class member:

Java
 




xxxxxxxxxx
1


 
1
private final Chat chatSession;


  1. Add the following constructor:

Java
 




xxxxxxxxxx
1


 
1
public ChatService() {
2
    BotConfiguration botConfiguration = BotConfiguration.builder()
3
            .name("alice")
4
            .path("src/main/resources")
5
            .build();
6
    Bot bot = new Bot(botConfiguration);
7
    chatSession = new Chat(bot);
8
}


  1. Add the following method to the class:

Java
 




xxxxxxxxxx
1


1
public String answer(String message) {
2
    return chatSession.multisentenceRespond(message);
3
}


Implementing the Web UI

To add a web UI to the application, you'll implement a UI component to show messages and a view. You'll also add CSS styles to make the application look like a typical online chat.

Implementing a Scrollable Message List

To implement a scrollable message list in Java:

  1. Create a new  MessageList  class.

  2. Implement the class as follows:

Java
 




xxxxxxxxxx
1
30


 
1
public class MessageList extends Div {
2
 
          
3
    public MessageList() {
4
        setClassName(getClass().getSimpleName());
5
    }
6
 
          
7
    public void addMessage(String from, Avataaar avatar, String text, boolean isCurrentUser) {
8
        Span fromContainer = new Span(new Text(from));
9
        fromContainer.addClassName(getClass().getSimpleName() + "-name");
10
 
          
11
        Div textContainer = new Div(new Text(text));
12
        textContainer.addClassName(getClass().getSimpleName() + "-bubble");
13
 
          
14
        Div avatarContainer = new Div(avatar, fromContainer);
15
        avatarContainer.addClassName(getClass().getSimpleName() + "-avatar");
16
 
          
17
        Div line = new Div(avatarContainer, textContainer);
18
        line.addClassName(getClass().getSimpleName() + "-row");
19
        add(line);
20
 
          
21
        if (isCurrentUser) {
22
            line.addClassName(getClass().getSimpleName() + "-row-currentUser");
23
            textContainer.addClassName(getClass().getSimpleName() + "-bubble-currentUser");
24
        }
25
 
          
26
        line.getElement().callJsFunction("scrollIntoView");
27
    }
28
 
          
29
}



To learn more about how to implement UI components with Vaadin see https://vaadin.com/learn/tutorials/vaadin-key-concepts.

Implementing a Chat View

To implement the chat view of the application:

  1. Open the ChatView class in your IDE.
  2. Remove the constructor.
  3. Add the following members to the class:
Java
 




xxxxxxxxxx
1


1
private final UI ui;
2
private final MessageList messageList = new MessageList();
3
private final TextField message = new TextField();
4
private final Chat chatSession;
5
private final ScheduledExecutorService executorService;



  1. Add the following constructor to the class:

Java
 




xxxxxxxxxx
1
19


1
public ChatView(Bot alice, ScheduledExecutorService executorService) {
2
    this.executorService = executorService;
3
    ui = UI.getCurrent();
4
    chatSession = new Chat(alice);
5
 
          
6
    message.setPlaceholder("Enter a message...");
7
    message.setSizeFull();
8
 
          
9
    Button send = new Button(VaadinIcon.ENTER.create(), event -> sendMessage());
10
    send.addClickShortcut(Key.ENTER);
11
 
          
12
    HorizontalLayout inputLayout = new HorizontalLayout(message, send);
13
    inputLayout.addClassName("inputLayout");
14
 
          
15
    add(messageList, inputLayout);
16
    expand(messageList);
17
    setSizeFull();
18
}



  1. Add the following method to the class:

Java
 




xxxxxxxxxx
1
10


1
private void sendMessage() {
2
    String text = message.getValue();
3
    messageList.addMessage("You", new Avataaar("Name"), text, true);
4
    message.clear();
5
 
          
6
        executorService.schedule(() -> {
7
            String answer = chatSession.multisentenceRespond(text);
8
            ui.access(() -> messageList.addMessage(
9
                    "Alice", new Avataaar("Alice2"), answer, false));
10
        },new Random().ints(1000, 3000).findFirst().getAsInt(),
11
                                 TimeUnit.MILLISECONDS);
12
}



Adding Custom Styles

To add custom CSS styles to the application:

  1. Open the  chat-view.css  file in your IDE.
  2. Add the following selectors and rules:
CSS
 




xxxxxxxxxx
1
44


1
.inputLayout {
2
    width: 100%;
3
}
4
 
          
5
.MessageList {
6
    overflow-y: scroll;
7
    width: 100%;
8
    height: 100%;
9
}
10
 
          
11
.MessageList-name {
12
    font-weight: bold;
13
}
14
 
          
15
.MessageList-bubble {
16
    margin: .5em;
17
    padding: 1em;
18
    border-radius: var(--lumo-border-radius-s);
19
    background-color: var(--lumo-shade-20pct);
20
}
21
 
          
22
.MessageList-bubble-currentUser {
23
    background-color: var(--lumo-primary-text-color);
24
    color: var(--lumo-base-color);
25
}
26
 
          
27
.MessageList-avatar {
28
    display: flex;
29
    flex-direction: column;
30
    align-items: center;
31
    width: unset;
32
    height: unset;
33
    padding: 0;
34
}
35
 
          
36
.MessageList-row {
37
    display: flex;
38
    align-items: center;
39
}
40
 
          
41
.MessageList-row-currentUser {
42
    flex-direction: row-reverse;
43
}



Building and Running the Application

The first time you build the application server-side and client-side dependencies are downloaded. This might take some time. However, subsequent builds are much faster.

To build and run the application execute the Application::main(String[])  standard Java application entry point in your IDE. Alternatively, you can execute the  java -jar target/vaadin-chat-1.0-SNAPSHOT.jar or  mvn spring-boot:run commands.

You can request the application in your browser at http://localhost:8080.

What to Do From Here?

The AIML format is very flexible and allows you to do many things. Try creating your AIML files around business or leisure topics or explore the many ready-made AIML that are available online. For example:

Try making two bots talk to each other. You can generate an initial phrase and see how the bots continue the conversation by themselves.

Keep in mind that In production environments you might have to move the .aiml files to an external directory similar to how you would do with other resources like databases. Also, in the case of Vaadin applications, use the production Maven profile to make the app ready for production environments.

Try the app on a mobile device. The Vaadin application you coded includes features of Progressive Web Application (PWA) which means, for example, that you can install it onto the home screen of your mobile device.

Check the Chat and Avatar components of the Vaadin ComponentFactory. These components help you to reduce the amount of code you have to write yourself when implementing this kind of application.

See the source code on GitHub.

Topics:
artificial inteeligence ,chat ,chatbot ,java ,machine learning ,vaadin ,web development

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}