https://howtodoinjava.
com/ai/java-aiml-chatbot-example/
Java chatbot example using aiml library
Last Updated On June 16, 2020
In this Java AIML tutorial, we will learn to create simple chatbot program in Java. A
Chatbot is an application designed to simulate the conversation with human users, especially
over the Internet. Internally it uses any NLP (Natural Language Processing) system to
interpret the human interactions and reply back with meaningful information.
AIML (Artificial Intelligence Markup Language) is an XML dialect for creating natural
language software agents. It contains the basic rules which Natural Language Understanding
(NLU) unit uses internally. It can be think of as a heart of the engine. The more rules we add
in AIML – the more intelligent our Chatbot will be.
It’s important to know the difference between NLP and NLU. NLP refers to all systems that
work together to handle end-to-end interactions between machines and humans in the
preferred language of the human. In other words, NLP lets people and machines talk to each
other “naturally”. NLU is actually a subset of the wider world of NLP. It helps in parsing
unstructured inputs e.g. mispronunciations, swapped words, contractions, colloquialisms, and
other quirks.
Table of Contents
1. Prerequisite
2. Java AIML Chatbot Example
3. Add Custom Patterns in Chatbot
4. Summary
1. Prerequisite
Reference AIML Implementation – To get started, we shall use an already working
reference application. There is one such java based implementation called program-
ab hosted on google-code repository. Download the program-ab latest distribution
from google code repository.
Eclipse and Maven – for coding and development.
2. Java AIML Chatbot Example
Follow these simple steps for building your first Chatbot application.
2.1. Download Unzip the program-ab distribution
We need to first unzip the program-ab distribution to a convenient folder. We will need to
take Ab.jar and existing AIML rules from it.
2.2. Create eclipse project
Create eclipse maven project to start the development. So let’s create a maven project with .
2.3. Create project and import AIML library
Create eclipse maven project to start the development. Choose packaging as jar and GAV
coordinate as your choice and import to eclipse. Now create a folder lib in the base folder
and copy the Ab.jar from the program-ab distribution to this folder.
2.4. Add AIML to classpath
To add AIML to classpath, add Ab.jar to deployment assembly in eclipse. Alternatively you
can install this jar into your local maven repository and then use it.
Add below AIML maven dependency to pom.xml. Now build the maven project by command
mvn clean install.
<dependencies>
<dependency>
<artifactId>com.google</artifactId>
<groupId>Ab</groupId>
<version>0.0.4.3</version>
<scope>system</scope>
<systemPath>${basedir}/lib/Ab.jar</systemPath>
</dependency>
</dependencies>
2.5. Copy default AIML rules
Copy the bots folder from program-ab directory into the resources folder of your maven
project. This folder contains default AIML sets that we will use initially. Later we will see
how we can add our custom rules into our Chatbot.
Project Structure with bots added to resources folder
2.6. Create Hello World Chatbot Program
Now create a simple java program i.e. Chatbot.java. It’s main() method will invoke the
chat program which will run on the command prompt. Basic structure of this program will be
to introduce a infinite loop and in each loop take a user input from command prompt and then
we will ask program-ab API to give the answer of the input provided by user.
More details about the program-ab API interaction is mentioned in the wiki link.
package com.howtodoinjava.ai;
import java.io.File;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.alicebot.ab.History;
import org.alicebot.ab.MagicBooleans;
import org.alicebot.ab.MagicStrings;
import org.alicebot.ab.utils.IOUtils;
public class Chatbot {
private static final boolean TRACE_MODE = false;
static String botName = "super";
public static void main(String[] args) {
try {
String resourcesPath = getResourcesPath();
System.out.println(resourcesPath);
MagicBooleans.trace_mode = TRACE_MODE;
Bot bot = new Bot("super", resourcesPath);
Chat chatSession = new Chat(bot);
bot.brain.nodeStats();
String textLine = "";
while(true) {
System.out.print("Human : ");
textLine = IOUtils.readInputTextLine();
if ((textLine == null) || (textLine.length() < 1))
textLine = MagicStrings.null_input;
if (textLine.equals("q")) {
System.exit(0);
} else if (textLine.equals("wq")) {
bot.writeQuit();
System.exit(0);
} else {
String request = textLine;
if (MagicBooleans.trace_mode)
System.out.println("STATE=" + request + ":THAT=" +
((History) chatSession.thatHistory.get(0)).get(0) + ":TOPIC=" +
chatSession.predicates.get("topic"));
String response =
chatSession.multisentenceRespond(request);
while (response.contains("<"))
response = response.replace("<", "<");
while (response.contains(">"))
response = response.replace(">", ">");
System.out.println("Robot : " + response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getResourcesPath() {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length() - 2);
System.out.println(path);
String resourcesPath = path + File.separator + "src" +
File.separator + "main" + File.separator + "resources";
return resourcesPath;
}
}
2.7. Test Chatbot Interactions
Now our program is ready and we can now start conversation with chat. To do that just run
the program as java application. To exit, you shall type q or wq.
Human : Hi
Robot : Hi! It's delightful to see you.
Human : How are you
Robot : Feeling really joyful today.
Human : My name is sajal
Robot : Glad to see you, Sajal
Human : what is my name
Robot : Sajal
Human : tell me my name
Robot : Sajal
Like this, you can do basic talk with the chat bot.
3. Add Custom Patterns in Chatbot
Now we can add our custom patterns in the bot to add more intelligence in the interactions.
To do that create a new .aiml file in the aiml directory of your bot (src\main\resources\
bots\super\aiml) . Add as many categories in that file as you wish. Here category refer to
the human questions and template refers to chat bot’s response. I have created a file called a-
custom-entry.aiml and added three questions as below.
<?xml version="1.0" encoding="UTF-8"?>
<aiml>
<category><pattern>WHAT IS JAVA</pattern>
<template>Java is a programming language.</template>
</category>
<category><pattern>WHAT IS CHAT BOT</pattern>
<template>Chatbot is a computer program designed to simulate
conversation with human users, especially over the
Internet.</template>
</category>
<category><pattern>WHAT IS INDIA</pattern>
<template>wonderful country.</template>
</category>
</aiml>
Now we can ask bot these three questions as well.
Once our custom aiml file is ready, we need to do generate corresponding entries for other
folders parallel to aiml. To do it, we need to invoke the bot.writeAIMLFiles(). I have
created another java program called AddAiml.java for this purpose. Once you are done with
the aiml editing, just run this program once before starting the bot. It will add these custom
entries to the bot’s brain.
package com.howtodoinjava.ai;
import java.io.File;
import org.alicebot.ab.Bot;
import org.alicebot.ab.MagicBooleans;
public class AddAiml {
private static final boolean TRACE_MODE = false;
static String botName = "super";
public static void main(String[] args) {
try {
String resourcesPath = getResourcesPath();
System.out.println(resourcesPath);
MagicBooleans.trace_mode = TRACE_MODE;
Bot bot = new Bot("super", resourcesPath);
bot.writeAIMLFiles();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getResourcesPath() {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length() - 2);
System.out.println(path);
String resourcesPath = path + File.separator + "src" +
File.separator + "main" + File.separator + "resources";
return resourcesPath;
}
}
3.1. Test custom chat patterns
After running the AddAiml, once you have added the new entries into the AIML, run the chat
bot program again and ask the new questions. It should give proper response.
In my case, here is the output.
Human : What is java
Robot : Java is a programming language.
Human : what is chat bot
Robot : Chatbot is a computer program designed to simulate
conversation with human users, especially over the
Internet.
Human : what is india
Robot : wonderful country.
4. Summary
In this AIML Java tutorial, we have learn to create simple command line based chatbot
program with program-ab reference application. Next time, when you have any such
requirement, you can think of AIML based chat bot. It is capable to doing moderate stuffs
easily.
To enhance your knowledge, you may try to –
Play with AIML and create more interesting conversations. AIML has many tags
which you can use, it also give some option to configure Sraix to invoke external
REST based web services.
Add your own custom placeholder in the template section and parse that from the
AIML response and do more based on your identifier in the response, like You can
able to invoke your own web service to get some more information.
Convert this command line chat program to web based chat, I am currently working
on that and will publish a followup post on that.
You can add your custom rule engine on top of your AIML response to do more.
AIML can do lots of things, but now a days much more sophisticated techniques are available
specially in the Machine Learning space, try to learn those as well.
I have deleted the Ab.jar file from this source code distribution due to the size restriction.
Please add the jar file from program-ab distribution that you have downloaded initially.
Download Java Chatbot Source Code
Happy Learning !!
Was this article helpful?
TwitterFacebookLinkedInRedditPocket
Previous Tutorial:
Next Tutorial:
Feedback, Discussion and Comments
1. kapil singh
April 21, 2020
SIr your web based Chatbot was build or not can you plz share with us
2. botUser
April 7, 2020
I came across such problem, let’s say I added few categories, ran AddAIML program,
tested them and they work fine, then I added few more categories and ran the
AddAIML program again, the problem is that it deletes the latest categories that I
added and restores the files so that the only categories that appear there are the very
first ones that i’ve created.
3. inthiyaj khan patan
January 26, 2020
An excellent article to begin with AIML. need more clarification on AIML code so
that we can customize it based on our requirement. i am looking for Web based bot.
4. Paul
May 19, 2019
great article . I would appreciate to get web based version
5. Ananda
May 15, 2019
Thanks Sajal. For All, I downloaded application from this link “Download Java
Chatbot Source Code” above and able to run application on eclipse(after importing
this maven project).
o Dheeraj
August 27, 2019
Could help me how to install it
6. Naresh Tekmalle
March 27, 2019
Guys try this project in intelij community edition it will work…..
7. Yogesh Katkar
March 14, 2019
how to track session if two users are concurrently chatting with bot?
8. Hariharan
January 25, 2019
Great leaning! Thanks
9. Shubhashri
October 25, 2018
what does MagicBooleans are for?Also, what files are written and where, by the
statement ” bot.writeAIMLFiles();”??
10. Sarvesh
October 16, 2018
Where can I look for documentation to understand this code ?
11. Pavan Patil
October 9, 2018
Exception in thread “main” java.lang.Error: Unresolved compilation problems:
MagicBooleans cannot be resolved to a variable
Bot cannot be resolved to a type
Bot cannot be resolved to a type
How to solve this error?
12. Ankit
August 16, 2018
Hi, were you able to convert it to a web based module?
o Vinod
January 3, 2020
Yes
Trupti
January 14, 2020
can you share how we can convert this code in web based module?
Mohamed
May 13, 2020
Hi Vinod, Can you let em know how you converted this to web ?
sharukhan
May 14, 2020
hi will u share how to convert it as web?
Servlet.service() for servlet [dispatcher] in context with path [/Insert]
threw exception [Handler dispatch failed; nested exception is
java.lang.NoClassDefFoundError: org/alicebot/ab/Bot] with root cause
java.lang.ClassNotFoundException: org.alicebot.ab.Bot
i got this error after converting this into web based…alicebot is not
working in web based module
someone help me to clear this error
13. Rahul
July 4, 2018
in the target folder there is two files .classpath and .project but this files not contain in
the source folder you are provided
also
when it runs it displays no main class
14. Anant Mane
June 17, 2018
How to stop bot going outside for getting response?
15. riyaz
May 26, 2018
how to convert this to web based chat?
16. Toufiq
December 14, 2017
How to solve this issue –
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at sun.security.ssl.SSLSessionImpl.getPeerCertificates(Unknown Source)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at
org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:57
2)
at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(Default
ClientConnectionOperator.java:180)
at
org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConn
ectionImpl.java:294)
at
org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirect
or.java:640)
at
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.j
ava:479)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at org.alicebot.ab.utils.NetworkUtils.responseContent(NetworkUtils.java:50)
at org.alicebot.ab.Sraix.sraixPannous(Sraix.java:111)
at org.alicebot.ab.Sraix.sraix(Sraix.java:42)
at org.alicebot.ab.AIMLProcessor.sraix(AIMLProcessor.java:385)
at org.alicebot.ab.AIMLProcessor.recursEval(AIMLProcessor.java:1050)
at org.alicebot.ab.AIMLProcessor.evalTagContent(AIMLProcessor.java:246)
at org.alicebot.ab.AIMLProcessor.recursEval(AIMLProcessor.java:1040)
at org.alicebot.ab.AIMLProcessor.evalTemplate(AIMLProcessor.java:1133)
at org.alicebot.ab.AIMLProcessor.respond(AIMLProcessor.java:187)
at org.alicebot.ab.AIMLProcessor.respond(AIMLProcessor.java:162)
at org.alicebot.ab.Chat.respond(Chat.java:115)
at org.alicebot.ab.Chat.respond(Chat.java:140)
at org.alicebot.ab.Chat.multisentenceRespond(Chat.java:165)
at com.Chatbot.main(Chatbot.java:41)
Robot : I used my lifeline to ask another robot, but he didn’t know.
I’m going to try a search
o Defi
September 26, 2018
Hi Toufiq,
Did you find an answer. I’m too getting same error message.
Saurabh Bhatteja
December 25, 2018
Hi Toufiq and Defi,
Did you find any resolution for this exception.
I’m also facing the same issue.
o Saurabh Bhatteja
December 25, 2018
Did you find any resolution for this issue ?
Mohamed Rizwan
March 16, 2019
Hey guys,
have you find solution for this error. I am also facing the same problem
. if anyone resolved it. please, update the method to resolve that.
Naresh Tekmalle
March 27, 2019
try this project in intelij community edition ..
Don Bosco Rayappan
August 18, 2019
Guys,
It’s trying to connect to a restful web services, which has SSL
enabled. As of now, it’s trying to hit
“https://ask.pannous.com/api” or
“https://weannie.pannous.com/api” for web service answers.
I will recommend those who want to build answer to it, either
go register and get a customer id and credentials in
http://www.alicebot.org or download the sources for
programab.jar and change the restful service url to your own.
Thanks
o Kapil Singh Rana
March 4, 2020
go get the solution bro i face same problem
o Kapil Singh Rana
March 4, 2020
plz reply if anyone get the solution of this error
17. kalyan
November 22, 2017
How can we maintain and retain (to be able to retrieve later) the state of a chat ??
Could we build the chat object through some id (session id) ??
o Naveen
December 19, 2017
Hi Kalyan,
Did you find the solution, even I am working on the same. I wanted to store
the chat session/context and retrieve later.
–Naveen
LAKSHMIPATHY M
May 30, 2018
Hi Naveen,
We can save the chat history if we are running application in eclipse
IDE
18. Matheus Lubarino
September 17, 2017
First, excelent article
I have a question, I did you example but when I create a new aiml file in PT-BR the
robot not understood my language. what’s up ?
Search Tutorials
Popular Tutorials
Java 14 Tutorial
Java 8 Tutorial
Java Tutorial
Java Collections
Java Concurrency
Java Date and Time
Java Examples
Spring Boot Tutorial
Hibernate Tutorial
Jersey Tutorial
Maven Tutorial
Log4j Tutorial
Regex Tutorial
Python Tutorial