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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Leverage Amazon BedRock Chat Model With Java and Spring AI
  • Exploring Embeddings API With Java and Spring AI
  • The Impact of Edge Computing on Mobile App Development

Trending

  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Implementing a Web Chat With AI in Java

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!

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Updated Oct. 01, 20 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
39.8K Views

Join the DZone community and get the full member experience.

Join For Free

This article shows step by step how to implement a web chatbot using Java. Here's a screenshot of the application you will develop:

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:

XML
 




xxxxxxxxxx
1
10


 
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).

Here's a screenshot of the project structure with the AIML files:

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
13


 
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
}



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:

  • https://github.com/pandorabots/Free-AIML
  • https://github.com/pandorabots/rosie
  • https://github.com/drwallace/aiml-en-us-foundation-alice

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.

AI Java (programming language) mobile app

Opinions expressed by DZone contributors are their own.

Related

  • Introducing SmallRye LLM: Injecting Langchain4J AI Services
  • Leverage Amazon BedRock Chat Model With Java and Spring AI
  • Exploring Embeddings API With Java and Spring AI
  • The Impact of Edge Computing on Mobile App Development

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!