Chatbot in Python
Chatbot in Python
Chatbot IN Python
An
Skill Development Project Report
on
“ChatBot Assistant System using Python”
Submitted in partial fulfilment for the award of degree of
Bachelor of Technology
in
Department of Electronics & Communication Engineering
i|Page
ii
iii
ACKNOWLEDGEMENT
There are always some key personalities whose roles are vital for the successful
completion of any work. However, it would not have been possible to complete
this work without the kind support and help of many individuals and organization.
I would like to extend my sincere thanks to all of them.
I would like to thank Prof. (Dr.) Mukesh Arora, Professor & Head, Department of
Electronics and communication, SKIT M & G, Jaipur for providing me the
opportunity to do training in consistent direction and the adequate means and
support to pursue this training.
Finally, earnest and sincere thanks to all the Faculty members of Electronics and
Communication Department, SKIT M & G, Jaipur for their direct and indirect
support in the completion of this industrial training.
Last but not least, I sincerely express my deepest gratitude to my families for their
wholehearted support and encouragement to take up this course. In addition, a very
special thanks to friends for their support.
Aditya Garg
19ESKEC005
iv
LIST OF FIGURES
vi
CONTENTS
Page No.
Acknowledgement ii
List of Figures iii
List of Tables iv
List of Abbreviations v
CHAPTER 1: INTRODUCTION
1.1 Abstract 1
1.2 Chatbot in Python 2
1.3 Artificial Intelligence 3-5
1.4 AI application 5-6
CHAPTER 2: CHATTERBOT
2.1 Understanding the ChatterBot Library 7
2.2 Understanding the working of ChatterBot Library
2.3 Creating a ChatBot using Python 8
vii
6.1 Conclusions 12
6.2 Scope for Future Research 13
REFERENCES
viii
CHAPTER 1
INTRODUCTION
1.1 ABSTRACT
A chatbot is a computer program that can converse with humans using artificial
intelligence in messaging platforms. The goal of the project is to add a chatbot feature
and API for Yioop. discussion groups, blogs, wikis etc. Yioop provides all the basic
features of web search portal. It has its own account management system with the ability
to set up groups that have discussions boards. Groups are collections of users that have
access to a group feed. The user who creates a group is set as the initial group owner.
Posts are grouped by thread in a group containing the most recent activity at the top. The
chatbot API for Yioop will allow developers to create new chatbots, powered by rules or
artificial intelligence, that can interact like a human with users in a groups feed page.
Example chatbots that can be developed with this API is weather chatbots or book flight
chatbots. Over past few years, messaging applications have become more popular than
Social networking sites. People are using messaging applications these days such as
Facebook Messenger, Skype, Viber, Telegram, Slack etc. This is making other
businesses available on messaging platforms leads to proactive interaction with users
about their products. To interact on such messaging platforms with many users, the
businesses can write a computer program that can converse like a human which is called
a chatbot.
We can categorize the Chatbots into two primary variants: Rule-Based Chatbots and Self-
Learning Chatbots.
1. Rule-based Chatbots: The Rule-based approach trains a chatbot to answer questions based
on a list of pre-determined rules on which it was primarily trained. These set rules can either
be pretty simple or quite complex, and we can use these rule-based chatbots to handle
simple queries but not process more complicated requests or queries.
2. Self-learning Chatbots: Self-learning chatbots are chatbots that can learn on their own.
These leverage advanced technologies such as Artificial Intelligence (AI) and Machine
Learning (ML) to train themselves from behaviours and instances. Generally, these chatbots
are quite smarter than rule-based bots. We can classify the Self-learning chatbots furtherly
into two categories - Retrieval-based Chatbots and Generative Chatbots.
1. Retrieval-based Chatbots: A retrieval-based chatbot works on pre-defined input
patterns and sets responses. Once the question or pattern is inserted, the chatbot
utilizes a heuristic approach to deliver the relevant response. The model based on
retrieval is extensively utilized to design and develop goal-oriented chatbots using
customized features such as the flow and tone of the bot in order to enhance the
experience of the customer.
2. Generative Chatbots: Unlike retrieval-based chatbots, generative chatbots are not
based on pre-defined responses - they leverage seq2seq neural networks. This is
constructed on the concept of machine translation, where the source code is
converted from one language to another language. In the seq2seq approach, the
input is changed into an output.
The first chatbot named ELIZA was designed and developed by Joseph Weizenbaum in 1966 that
could imitate the language of a psychotherapist in only 200 lines of code. But as the technology gets
more advance, we have come a long way from scripted chatbots to chatbots in Python today.
AI was coined by John McCarthy, an American computer scientist, in 1956 at The Dartmouth
Conference where the discipline was born. Today, it is an umbrella term that encompasses
everything from robotic process automation to actual robotics. It has gained prominence recently
due, in part, to big data, or the increase in speed, size and variety of data businesses are now
collecting. AI can perform tasks such as identifying patterns in the data more efficiently than
humans, enabling businesses to gain more insight out of their data.
AI can be categorized in any number of ways, but here are two examples.
The first classifies AI systems as either weak AI or strong AI. Weak AI, also known as narrow AI,
is an AI system that is designed and trained for a particular task. Virtual personal assistants, such
as Apple's Siri, are a form of weak AI.
Strong AI, also known as artificial general intelligence, is an AI system with generalized human
cognitive abilities so that when presented with an unfamiliar task, it has enough intelligence to
find a solution. The Turing Test, developed by mathematician Alan Turing in 1950, is a method
used to determine if a computer can actually think like a human, although the method is
controversial.
The second example is from Arend Hintze, an assistant professor of integrative biology and
computer science and engineering at Michigan State University. He categorizes AI into four types,
from the kind of AI systems that exist today to sentient systems, which do not yet exist. His
categories are as follows:
Examples of AI technology
Automation is the process of making a system or process function automatically. Robotic process
automation, for example, can be programmed to perform high-volume, repeatable tasks normally
performed by humans. RPA is different from IT automation in that it can adapt to changing
circumstances.
Machine learning is the science of getting a computer to act without programming. Deep learning
is a subset of machine learning that, in very simple terms, can be thought of as the automation of
predictive analytics. There are three types of machine learning algorithms: supervised learning, in
which data sets are labeled so that patterns can be detected and used to label new data sets;
unsupervised learning, in which data sets aren't labeled and are sorted
according to similarities or differences; and reinforcement learning, in which data sets aren't
labeled but, after performing an action or several actions, the AI system is given feedback.
Machine vision is the science of making computers see. Machine vision captures and analyzes
visual information using a camera, analog-to-digital conversion and digital signal processing. It
is often compared to human eyesight, but machine vision isn't bound by biology and can be
programmed to see through walls, for example. It is used in a range of applications from signature
identification to medical image analysis. Computer vision, which is focused on machine-based
image processing, is often conflated with machine vision.
Natural language processing (NLP) is the processing of human -- and not computer -- language by
a computer program. One of the older and best known examples of NLP is spam detection, which
looks at the subject line and the text of an email and decides if it's junk. Current approaches to NLP
are based on machine learning. NLP tasks include text translation, sentiment analysis and speech
recognition.
Pattern recognition is a branch of machine learning that focuses on identifying patterns in data.
The term, today, is dated.
Robotics is a field of engineering focused on the design and manufacturing of robots. Robots are
often used to perform tasks that are difficult for humans to perform or perform consistently. They
are used in assembly lines for car production or by NASA to move large objects in space. More
recently, researchers are using machine learning to build robots that can interact in socialsettings.
1.4 AI applications
AI in healthcare. The biggest bets are on improving patient outcomes and reducing costs.
Companies are applying machine learning to make better and faster diagnoses than humans. One
of the best known healthcare technologies is IBM Watson. It understands natural language and is
capable of responding to questions asked of it. The system mines patient data and other available
data sources to form a hypothesis, which it then presents with a confidence scoring schema. Other
AI applications include chatbots, a computer program used online to answer questions and assist
customers, to help schedule follow-up appointments or aiding patients through the billing process,
and virtual health assistants that provide basic medical feedback.
AI in business. Robotic process automation is being applied to highly repetitive tasks normally
performed by humans. Machine learning algorithms are being integrated into analytics and CRM
platforms to uncover information on how to better serve customers. Chatbots have been
incorporated into websites to provide immediate service to customers. Automation of job positions
has also become a talking point among academics and IT consultancies such as Gartner and
Forrester.
AI in education. AI can automate grading, giving educators more time. AI can assess students
and adapt to their needs, helping them work at their own pace. AI tutors can provide additional
support to students, ensuring they stay on track. AI could change where and how students learn,
perhaps even replacing some teachers.
AI in finance. AI applied to personal finance applications, such as Mint or Turbo Tax, is upending
financial institutions. Applications such as these could collect personal data and provide financial
advice. Other programs, IBM Watson being one, have been applied to the process of buying a
home. Today, software performs much of the trading on Wall Street.
AI in law. The discovery process, sifting through of documents, in law is often overwhelming for
humans. Automating this process is a better use of time and a more efficient process. Startups are
also building question-and-answer computer assistants that can sift programmed-to-answer
questions by examining the taxonomy and ontology associated with a database.
AI in manufacturing. This is an area that has been at the forefront of incorporating robots into the
workflow. Industrial robots used to perform single tasks and were separated from human workers,
but as the technology advanced that changed.
CHAPTER 2
Another amazing feature of the ChatterBot library is its language independence. The library
is developed in such a manner that makes it possible to train the bot in more than one
programming language.
When a user inserts a particular input in the chatbot (designed on ChatterBot), the bot saves
the input and the response for any future usage. This information (of gathered experiences)
allows the chatbot to generate automated responses every time a new input is fed into it.
The program picks the most appropriate response from the nearest statement that matches
the input and then delivers a response from the already known choice of statements and
responses. Over time, as the chatbot indulges in more communications, the precision of
reply progresses.
We will follow a step-by-step approach and break down the procedure of creating a Python
chat.
We will begin building a Python chatbot by importing all the required packages and modules
necessary for the project. We will also initialize different variables that we want to use in it.
Moreover, we will also be dealing with text data, so we have to perform data preprocessing
on the dataset before designing an ML model.
This is where tokenizing supports text data - it converts the large text dataset into smaller,
readable chunks (such as words). Once this process is complete, we can go for lemmatization
to transform a word into its lemma form. Then it generates a pickle file in order to store the
objects of Python that are utilized to predict the responses of the bot.
Another major section of the chatbot development procedure is developing the training and
testing datasets.
CHAPTER 3
PROBLEM IDENTIFICATION
• Lacking of training data. The quantity and quality of training data is critical to the
performance to a machine learning model. However, because some
confidential and privacy reasons, the business team cannot provide enough data for us, and
we had to make up data by our own. For the machine learning model, we generate some
fake data based on our daily life experience, which is really biased, although with a good
accuracy on the fake dat.
• Unstable API version. Because API service we are using are still under
development, and we cannot fix to a version for the API, the API may changes
overtime. Moreover, there are inconsistencies between the APIs and their
documents or sample codes.
• Not familiar with the PHP language and .NET framework. None of the three of us
has previous knowledge with PHP language. Programming in a new language in such
a huge framework is quite challenging for us at the beginning of the project. However,
when we comes to the later phases, we are more used to that.
CHAPTER 4
CHAPTER 5
PROPOSED SOLUTION
The next step is to create a chatbot using an instance of the class "ChatBot" and train the bot
in order to improve its performance. Training the bot ensures that it has enough knowledge, to
begin with, particular replies to particular input statements.
File: my_chatbot.py
# creating a chatbot
myBot = ChatBot(
name = 'Sakura',
read_only = True,
logic_adapters = [
'[Link]',
'[Link]'
]
)
Explanation:
In the above snippet of code, we have defined a variable that is an instance of the class
"ChatBot". We have included various parameters within the class. The first parameter, 'name',
represents the name of the Python chatbot. Another parameter called 'read_only' accepts a
Boolean value that disables (TRUE) or enables (FALSE) the ability of the bot to learn after the
training. We have also included another parameter named 'logic_adapters' that specifies the
adapters utilized to train the chatbot.
Since we have to provide a list of responses, we can perform it by specifying the lists of strings
that we can use to train the Python chatbot and find the perfect match for a certain query. Let
us consider the following example of responses we can train the chatbot using Python to learn.
File: my_chatbot.py
11 | P a g e
math_convo_1 = [
'Pythagorean theorem',
'a squared plus b squared equals c squared.'
]
math_convo_2 = [
'Law of Cosines',
'c**2 = a**2 + b**2 - 2*a*b*cos(gamma)'
]
Explanation:
In the above snippet of code, we have defined some list of responses in order to train the
chatbot. We can also create and train the chatbot by simple typing an instance of "ListTrainer"
and providing it with a list of strings as shown below:
File: my_chatbot.py
list_trainee.train(i)
Explanation:
In the above snippet of code, we have created an instance of the ListTrainer class and used
the for-loop to iterate through each item present in the lists of responses.
We can use the get_response() function in order to interact with the Python chatbot. Let us
consider the following execution of the program to understand it.
Output:
# starting a conversation
>>> print(myBot.get_response("Hi, there!"))
Hi
>>> print(myBot.get_response("What's your name?"))
I'm Sakura. Ask me a math question, please.
>>> print(myBot.get_response("Do you know Pythagorean theorem"))
a squared plus b squared equals c squared.
>>> print(myBot.get_response("Tell me the formula of law of cosines"))
c**2 = a**2 + b**2 - 2*a*b*cos(gamma)
Explanation:
The above execution of the program tells us that we have successfully created a chatbot in
Python using the chatterbot library. However, it is also necessary to understand that the
chatbot using Python might not know how to answer all the queries. Since its knowledge and
training are still very limited, we have to provide it time and give more training data to train it
further.
As we move to the final step of creating a chatbot in Python, we can utilize a present corpus of
data to train the Python chatbot even further.
Let us consider the following example of training the Python chatbot with a corpus of data given
by the bot itself.
File: my_chatbot.py
13 | P a g e
Explanation:
In the above snippet of code, we have imported the ChatterBotCorpusTrainer class from
the [Link] module. We created an instance of the class for the chatbot and set
the training language to English.
Moreover, from the last statement, we can observe that the ChatterBot library provides
this functionality in multiple languages. Thus, we can also specify a subset of a corpus
in a language we would prefer. Hence, our chatbot in Python has been created.
14 | P a g e
# creating a chatbot
myBot = ChatBot(
name = 'Sakura',
read_only = True,
logic_adapters = [
'[Link]',
'[Link]'
]
)
math_convo_1 = [
15 | P a g e
'Pythagorean theorem',
'a squared plus b squared equals c squared.'
]
math_convo_2 = [
'Law of Cosines',
'c**2 = a**2 + b**2 - 2*a*b*cos(gamma)'
]
16 | P a g e
17 | P a g e
CHAPTER 6
IMPLEMENTATION
Implementation
This section covers the design and implementation of different module of the bot, which
contains the design of the PYTHON module, the Translator API and the AIML module..
18 | P a g e
19 | P a g e
Chatbot Interface
20 | P a g e
21 | P a g e
CHAPTER 7
ADVANTEGES & DISADVANTEGES
7.1 Advantages
1. Accessible anytime:
I’m sure most of you are always kept on hold while operators connect you to a customer
care executive. On an average people spend around 7 minutes until they are assigned to
a person. Gone are the frustrating days of waiting in a queue for the next available
operative. They are replacing live chat and other forms of slower contact methods such
as emails and phone calls. Since chatbots are basically virtual robots they never get tired
and continue to obey your command. They will continue to operate every day
throughout the year without requiring to take a break. This improves your customer UX
and helps you rank highly in your sector. Another advantage of this instant response is
that you can also skillfully craft your chatbot to maintain your image and brand.
2. Handling Capacity:
Unlike humans who can only communicate with one human at a time, chat bots can
simultaneously have conversations with thousands of people. No matter what time of
the day it is or how many people are contacting you, every single one of them will be
answered immediately.
Imagine you own a restaurant, and you have a good reputation for your food of which
most of your revenues come from delivery. As the demand keeps rising, you will have
more customers to take orders from but very few staff to attend them all. Having a
chatbot would eliminate such problem and cater to each and every person and ensure
that no order is missed. Companies like Taco Bell and Dominos are already using
chatbots to arrange delivery of parcels.
3. Flexible attribute:
22 | P a g e
Chatbots have the benefit that it can quite easily be used in any industry. Unlike other
products where you have to do a lot of development and testing to change platforms,
chatbots are relatively easy to switch. One has to just train the bot by giving the right
conversation structure and flow to switch its current field or industry.
Or if there is a lot of back and forth between two sections of the industry say
customer support and sales, then you could have custom built presets which would
already have the conversation flow and structure to carry out the interactions with the
user.
23 | P a g e
4. Customer Satisfaction:
Humans are bound to change of emotions. Chatbots, on the other hand, are bound by
some rules and obey them as long as they’re programmed to. They will always treat a
customer in the perfect way no matter how rough the person is or how foul language the
person uses.
Not everyone orders the same food everyday, people’s choices may change everyday.
In this case, it can use your order history to make suggestions for the next order, learn
your address details and much more. Customers love this smooth interaction and want
all their transactions to be as simple as possible.
5. Cost Effective:
Hiring a human for a job is never a cheap affair, and it will be expensive if your revenue
are not high or sales targets are not met and would create havoc in the business. Due to
the boundaries of human beings, a single human can only handle one or two people at
the same time. More than that would be extremely tough for the employee.
Chatbots could help solve this age-old problem. As one chatbot is equal to loads of
employees, it can easily communicate with thousands of customers at the same time.
We would only need a handful of people to jump into conversations sometimes when
necessary. Hence, it would drastically bring down the expenses and bring about a steep
rise in revenue and customer satisfaction.
6. Faster Onboarding:
Before you want to accomplish a task, you first must learn how to work on the task and
complete it. Only then will they be considered fit for the job. There is a continuous
teaching involved in every level of hierarchy the employee will go through. Also, there
will be a lot of change in the employees, some stay, some get fired, some more join in
etc.
What we want to say is, employees will change; it’s a fact. And this would require you
to allot a lot time of your employees into grooming the new joinees. Chatbots could
24 | P a g e
eliminate that time to almost zero, but provide a very clean and easy to understand
conversation flow and structure that needs to be maintained by the chatbot. No doubt
there will be changes in
this too, but it will rather take a fraction of your time to resolve as compared to human
employees.
25 | P a g e
7.2 Disadvantages-
Most of developers strive to create a universal chatbot that will become a fully-fledged
assistant to user. But in practice functional bots turn out not to cope with the majority
of queries. They often do not understand the user, forget what they were told 5 minutes
earlier, and have many other disadvantages. And that is no wonder, as the development
of a universal bot, which would understand natural language and could evaluate context,
takes years of hard work for a team of experienced programmers. And even in this
case, such programs should be constantly improved while in service.
However, modern technologies allow building rather useful bots to perform specific
actions such as booking train tickets or providing support to bank customers.
2. Primitive algorithms
3. Complex interface
Talking to a bot implies talking in a chat, meaning that a user will have to write a lot. And in
case a bot cannot understand the user’s request, he will have to write even more. It takes time
26 | P a g e
to find out which commands a bot can respond to correctly, and which questions are
better avoid. Thus, talking to a chatbot does not save time in the majority of cases.
Perhaps the efficiency of virtual assistants will increase due to the implementation of
voice recognition function in the future. But for the time being their functional
capabilities are very restricte, and they can be truly useful only in a few business
27 | P a g e
28 | P a g e
CHAPTER 9
CONCLUSION AND FUTURE SCOPE
9.1 Conclusions
Chatbots are the new Apps! As we have discussed in the above deliverables, this project brings
the power of chatbots to Yioop and enriches its usability. Chatbots in Yioop can give a human
like touch to some aspects and make it an enjoying conversation. And they are focused entirely
on providing information and completing tasks for the humans they interact with. The above
mentioned functionality in all the deliverables is implemented and pushed in to Yioop code.
By implementing the above mentioned deliverables I was able to add a basic chatbot
functionality in to the Yioop. I.e., configuring and creating accounts for bot users with bot
settings which is mentioned in deliverable 2, activating a bot whenever a user asks for it via
post in a thread which is discussed in deliverable 3 and as I discussed in deliverable 4, I have
implemented a simple weather chatbot that gives weather information whenever a user ask and
Fig. 3 tells that I was also able to converse with the bot in Yioop. I intend to enhance the system
developed so far in CS298. Next step towards building chatbots involve helping people to
facilitate their work and interact with computers using natural language or using set of rules.
Future Yioop chatbots, backed by machine-learning technology, will be able to remember past
conversations and learn from them to answer new ones. The challenge would be conversing
with multiple bot users and multiple user
There are limitations to what has been currently achieved with chatbots. The limitations of data
processing and retrieval are hindering chatbots to reach their full potential. It is not that we lack
the computational processing power to do so. However, there is a limitation on “How” we do
it. One of the biggest examples is the retail customer market. Retail customers are primarily
interested in interacting with humans because of nature of their needs. They don’t want bots to
process their needs and respond accor
29 | P a g e
References
1. Bayan Abu Shawar and Eric Atwell, 2007 “Chatbots: Are they Really Useful?”
2. LDV Forum - GLDV Journal for Computational Linguistics and Language
Technology.
3. [Link]
4. Bringing chatbots into education: Towards natural language negotiation of openlearner
models. Know.-Based Syst. 20, 2 (Mar. 2007), 177-185.
5. Intelligent Tutoring Systems: Prospects for Guided Practice and Efficient Learning.
Whitepaper for the Army's Science of Learning Workshop, Hampton, VA. Aug 1-
3, 2006.
6. [Link]
7. ALICE. 2002. A.L.I.C.E AI Foundation, [Link]
30 | P a g e