0% found this document useful (0 votes)
326 views48 pages

Chatbot Project Report

The document is a minor project report on creating a simple chatbot using Python and AI, submitted for a Bachelor of Technology degree in Computer Science and Engineering. It includes sections on project declaration, acknowledgments, an abstract explaining the chatbot's functionality, and a detailed table of contents outlining the project's structure. The report emphasizes the use of Natural Language Processing (NLP) to enhance user interaction and efficiency in customer service applications.

Uploaded by

ritiksharma4451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
326 views48 pages

Chatbot Project Report

The document is a minor project report on creating a simple chatbot using Python and AI, submitted for a Bachelor of Technology degree in Computer Science and Engineering. It includes sections on project declaration, acknowledgments, an abstract explaining the chatbot's functionality, and a detailed table of contents outlining the project's structure. The report emphasizes the use of Natural Language Processing (NLP) to enhance user interaction and efficiency in customer service applications.

Uploaded by

ritiksharma4451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

A SIMPLE CHATBOT In PYTHON USING AI

Minor Project Report

Submitted in Partial Fulfillment of the Requirement for the Award of the Degree

of

BACHELOR OF TECHNOLOGY
IN

COMPUTER SCIENCE AND ENGINEERING

Submitted by

ARTI SHARMA(22-CSE-2021)
ROUNAQ WANI(02-CSE-2021)
TOIBA ASHRAF(33-CSE\L-2022)
Under the Guidance of
Miss Pallavi Sharma

SCHOOL OF ENGINEERING & TECHNOLOGY

BABA GHULAM SHAH BADSHAH UNIVERSITY


RAJOURI (J & K) - 185234
July 2024
DECLARATION
I hereby declare that the project entitled “A Simple Chatbot In Python Using AI”
submitted for the B. Tech. (CSE) degree is my original work completed under the
supervision of ”Miss Pallavi Sharma”. To the best of my knowledge the project has not
formed the basis for the award of any other degree, diploma, fellowship or any other
similar titles.

Place: Baba Ghulam Shah Badshah Signature of the Student


University Rajouri

Date:
CERTIFICATE

This is to certify that the project titled “A Simple Chatbot In Python Using AI”
is the bonafide work carried out by Rounaq Wani(02-CSE-2021), a student of B Tech
(CSE) in School of Engineering and Technology, Baba Ghulam Shah Badshah University,
Rajouri, J&K, during the academic year 2024, in partial fulfillment of the requirements
for the award of the degree of Bachelor of Technology (Computer Science and
Engineering ) and to the best of my knowledge, the project has not formed the basis for
the award of any other degree.

Place:Baba Ghulam Shah University Rajouri

Date:

Signature of the Guide Signature of HoD

Signature of External Examiner


ACKNOWLEDGEMENT

I have taken efforts in this project. However, it would not have been possible without the kindsupport
and help of many individuals and organizations. I would like to extend my sincere thanksto all of them.I
am highly indebted to Mr. Khalil Ahmed(H.O.D, CSE Department) , Mr. Amit Dogra (Project Head)
and Miss Pallavi Sharma (Project Guide) for their guidance and constant supervision as well as for
providing necessary information regarding the project & also for their support in completing the
project.I would like to express my gratitude towards my parents & member of Institute of Computer
Science And Engineering for their kind co-operation and encouragement which help me in completion
of this project.I would like to express my special gratitude and thanks to my team members who work
hard to complete this project on time with me.My thanks and appreciations also go to my colleague in
developing the project and people whohave willingly helped me out with their abilities.I have taken
efforts in this project. However, it would not have been possible without the kind support and help of
many individuals . I would like to extend my sincere thanks to all of them.
ABSTRACT

A chatbot is a computer program that simulates and processes human conversation allowing humans to
interact with digital devices as if they were communicating with a real person.Chatbots can be as simple
as rudimentary programs that answer a simple query with a single-line response, or as sophisticated as
digital assistants that learn and evolve to deliver increasing levels of personalization as they gather and
process information.Chatbots help in customer support, generating information, user navigation
etc.,Organizations looking to increase sales or service productivity may adopt chatbots for time savings
and efficiency, as artificial intelligence (AI) chatbots can converse with users and answer recurring
questions. As consumers move away from traditional forms of communication, many experts expect
chat-based communication methods to rise.Organizations increasingly use chatbot-based virtual
assistants to handle simple tasks,allowing human agents to focus on other responsibilities.In this project
we will use Python to build a simple chatbot that can interact with users. Here we make use of AI and
Natural Language Processing in Python to create and train a chatbot to respond appropriately to an user
requests. Natural Language Processing (NLP) makes it possible for computers to understand the human
language. Behind the scenes, NLP analyzes the grammatical structure of sentences and the individual
meaning of words, then uses algorithms to extract meaning and deliver outputs. In other words, it makes
sense of human language so that it can automatically perform different tasks. A well-known application
of NLP is chatbots. They help support teams solve issues by understanding common language requests
and responding automatically.
TABLE OF CONTENTS

Chapter Number Title Page Number

1 Introduction 1
1.1.Overview of the Project
1.2.Scope and Objective

2 Literature Survey 2-6


2.1. Introduction
2.2. Literature Survey

3 System Design 7-9


3.1. Natural Language Processing
3.2. Advantages of NLP
3.3. Disadvantages of NLP
3.4. Architecture Diagram
3.5. Hardware Requirement
3.6. Software Requirement

4 Aalysis 10-13
4.1. Python Library
4.2. Data
4.3. Software Description
4.3.1. Python
4.3.2. Google Colab Notebook For Python

5 Creation of Chatbot 14-18


5.1. File Structure
5.2. Steps to create Chatbot

6 Implementation of code 19-37


6.1. Chatbot Sample code

7 Conclusion 38

8 Reference 39-40

LIST OF FIGURES USED

Fig 3.1. Architecture Diagram 10

Fig 5.1. Sample Output 18

Fig 6.1.1. Chatbot .ipynb Output 1 33

Fig 6.1.2. Chatbot.ipynb Output 2 34

Fig 6.1.3. Chatbotipynb Output 3 35

Fig 6.1.4. Chatbotipynb Output 4 36

Fig 6.1.5. Chatbot.ipynb Output 5 37


CHAPTER 1. INTRODUCTION

1.1.OVERVIEW OF THE PROJECT

A chatbot is a way of solving a user’s by interacting with a computer program . C hatbots and other
virtual methods of commmnication are becoming more popular as people turn away from more
conventional forms of communication. Chatbots provide a way for people to get their queries answered
virtually without having to correspond to emails or talk on the phone with a customer service
person.Chatbots can be adopted by an organization to increase their time efficiency as AI-based chatbots
can answer customers recurring questions easily.

1.2. SCOPE AND OBJECTIVE

SCOPE
The goal of the chatbot is to respond as precisely as possible to user questions.The user should be able to
receive the clearest possible responses to their inquiries.

OBJECTIVE
The main aim of the project is to provide the users with a platform to get their questions and queries
answered in a easy and simple way . This chatbot is a way for users to get their queries responses of day-
to-day usual conversations.Here we train the chatbot to recognize multiple types of words and phrases
related to a particular question in order to provide as proper answers to the users question as possible.

Major Functionalities Of The System


⚫ Conversation Between User and Bot
⚫ Interaction Between User and Bot
CHAPTER 2. LITERATURE SURVEY

2.1. INTRODUCTION
A literature survey or a literature review in a project report is that section which shows various analysis
and research made in the field of your interest and the results already published, taking into account the
various parameters of the project and the extent of project.Once the programmers start building the tool
programmers need a lot of external support.This support can be obtained from senior programmers,
books or from the websites. It is the most important part of your report as it gives you a direction in the
area of your research. It helps you set a goal for your analysis - thus giving you your problem of
statement. Literature survey is the most important sector in the software development process. Before
developing the tools and the associated designing the software it is necessary to determine the survey the
time factor, resource requirement etc., The consumer needs regarding online customer service differs
from person to person. The needs are also based off each persons personal needs. We need to identify
and anticipate these needs in order to completely and accurately meet them.

2.2.Literature Survey .
1.An Overview of Chatbot Technology
Eleni Adamopoulou and Lefteris Moussiades. 2020. An Overview of Chatbot Technology. An Overview
of Chatbot Technology | SpringerLink. Retrieved November
28,2022fromhttps://link.springer.com/chapter/10.1007/978-3-030-49186-4_31
Artificial Intelligence (ΑΙ) increasingly integrates our daily lives with the creation and analysis of
intelligent software and hardware, called intelligent agents. Intelligent agents can do a variety of tasks
ranging from labor work to sophisticated operations. A chatbot is a typical example of an AI system and
one of the most elementary and widespread examples of intelligent Human-Computer Interaction (HCI)
[1]. It is a computer program, which responds like a smart entity when conversed with through text or
voice and understands one or more human languages by Natural Language Processing (NLP) [2]. In the
lexicon, a chatbot is defined as “A computer program designed to simulate conversation with human
users,especially over the Internet” [3]. Chatbots are also known as smart bots, interactive agents,digital
assistants, or artificial conversation entities.Chatbots can mimic human conversation and entertain users
but they are not built only for this. They are useful in applications such as education, information
retrieval, business, and e-commerce [4]. They became so popular because there are many advantages of
chatbots for users and developers too. Most implementations are platform-independent and instantly
available to users without needed installations. Contact to the chatbot is spread through a user's social
graph without leaving the messaging app the chatbot lives in, which provides and guarantees the user’s
identity. Moreover, payment services are integrated into the messaging system and can be used safely
and reliably and a notification system re-engages inactive users. Chatbots are integrated with group
conversations or shared just like any other contact, while multiple conversations can be carried forward
in parallel. Knowledge in the use of one chatbot is easily transferred to the usage of other chatbots, and
there are limited data requirements. Communication reliability, fast and uncomplicated development
iterations, lack of version fragmentation, and limited design efforts for the interface are some of the
advantages for developers too.

2. AI-based Chatbot Service for Financial Industry - Takuma Okuda ,Sanae Shoda
Introducing automation through the use of a chatbot makes it possible to respond to customer inquiries
24/7. For example, applying a chatbot to a business in which operators make up a
big percentage of human resources as in a call center has the potential of making business operations
vastly more efficient. However, automating by chatbots has not yet reached a point at which all requests
can be handled, so there is a need to establish and apply technology that can satisfy service
requirements. With this in mind, Fujitsu has undertaken the development of a hybrid chatbot that is
capable of combining technologies such as rule based scenarios, FAQ searching, and text mining with
machine learning. This paper describes trends and examples surrounding the business application of
chatbots and presents the features of a chatbot product developed by Fujitsu for the financial industry.

3. Rule-Based Chatbot Integration into Software Engineering Course


Binkis, Mikas, et al. “Rule-Based Chatbot Integration Into Software Engineering Course.” Rule- Based
Chatbot Integration Into Software Engineering Course | SpringerLink, 7 Oct.
2021,link.springer.com/chapter/10.1007/978-3-030-88304-1_29.
A Chatbot refers to software that can perform services based on commands or answers given by a user
during an online conversation. Chatbots are applied in different areas ranging from pure entertainment
solutions to learning support systems. In this article, we investigate Chatbot systems as a way to support
learners during educational video sessions. We propose a rule-based Chatbot system that uses speech
recognition and synthesized answers for increased immersiveness and for supporting the learners with
different sensual perceptions.We introduce the design methodology we followed while creating a
Chatbot system, explain the Chatbot behavior from learner and teacher perspectives and describe the
system structure.The system was validated using the System Usability Scales (SUS) methodology. It
shows that the current implementation has an average usability score; therefore, it needs improvement.
On the other hand, the survey shows a positive learners attitude towards the proposed system.

4. An overview of artificial intelligence based chatbots and an example chatbot application


N. Albayrak, A. Özdemir and E. Zeydan, "An overview of artificial intelligence based chatbots and an
example chatbot application," 2018 26th Signal Processing and Communications Applications
Conference (SIU), 2018, pp. 1-4, doi:10.1109/SIU.2018.8404430.
ChatBot can be described as software that can chat with people using artificial intelligence.These
software are used to perform tasks such as quickly responding to users, informing them, helping to
purchase products and providing better service to customers. In this paper,we present the general
working principle and the basic concepts of artificial intelligence based chatbots and related concepts as
well as their applications in various sectors such as telecommunication, banking, health, customer call
centers and e-commerce. Additionally, the results of an example chatbot for donation service developed
for telecommunication service provider are presented using the proposed architecture.

5. AI-based chatbots in customer service and their effects on user compliance


Adam, Martin, et al. “AI-based Chatbots in Customer Service and Their Effects on User Compliance-
Electronic Markets.” SpringerLink, 17 Mar. 2020, link.springer.com/article/10.1007/s12525-020-00414-
7
Communicating with customers through live chat interfaces has become an increasingly popular means
to provide real-time customer service in many e-commerce settings. Today,human chat service agents
are frequently replaced by conversational software agents or chatbots, which are systems designed to
communicate with human users by means of natural language often based on artificial intelligence (AI).
Though cost- and time-saving opportunities triggered a widespread implementation of AI-based
chatbots, they still frequently fail to meet customer expectations, potentially resulting in users being less
inclined to comply with requests made by the chatbot. Drawing on social response and commitment-
consistency theory, we empirically examine through a randomized online experiment how verbal
anthropomorphic design cues and the foot-in-the-door technique affect user request compliance. Our
results demonstrate that both anthropomorphism as well as the need to stay consistent significantly
increase the likelihood that users comply with a chatbot’s request for service feedback. Moreover, the
results show that social presence mediates the effect of anthropomorphic design cues on user
compliance.
Communicating with customers through live chat interfaces has become an increasingly popular means
to provide real-time customer service in e-commerce settings. Customers use these chat services to
obtain information (e.g., product details) or assistance (e.g., solving technical problems). The real-time
nature of chat services has transformed customer service into a two-way communication with significant
effects on trust, satisfaction, and repurchase as well as WOM intentions (Mero 2018). Over the last
decade, chat services have become the preferred option to obtain customer support (Charlton 2013).
More recently, and fueled by technological advances in artificial intelligence (AI), human chat service
agents are frequently replaced by conversational software agents (CAs) such as chatbots, which are
systems such as chatbots designed to communicate with human users by means of natural language (e.g.,
Gnewuch et al. 2017; Pavlikova et al. 2003; Pfeuffer et al. 2019a). Though rudimentary CAs emerged as
early as the 1960s (Weizenbaum 1966), the “second wave of artificial intelligence” (Launch bury 2018)
has renewed the interest and strengthened the commitment to this technology, because it has paved the
way for systems that are capable of more human-like interactions (e.g., Gnewuch et al. 2017; Maedche
et al. 2019; Pfeuffer et al.2019b). However, despite the technical advances, customers continue to have
unsatisfactory encounters with CAs that are based on AI. CAs may, for instance, provide unsuitable
responses to the user requests, leading to a gap between the user’s expectation and the system’s
performance (Luger and Sellen 2016; Orlowski 2017). With AI-based CAs displacing human chat
service agents, the question arises whether live chat services will continue to be effective, as skepticism
and resistance against the technology might obstruct task completion and inhibit successful service
encounters. Interactions with these systems might thus trigger unwanted behaviors in customers such as
a noncompliance that can negatively affect both the service providers as well as users (Bowman et al.
2004).
However,if customers choose not to conform with or adapt to the recommendations and requests given
by the CAs this calls into question the raison d’être of this self-service technology (Cialdini and
Goldstein 2004).To address this challenge, we employ an experimental design based on an AI-based
chatbot(hereafter simply “chatbot”), which is a particular type of CAs that is designed for turn-by-turn
conversations with human users based on textual input. More specifically, we explore what
characteristics of the chatbot increase the likelihood that users comply with a chatbot’s request for
service feedback through a customer service survey. We have chosen this scenario to test the user’s
compliance because a customer’s assessment of service quality is important and a universally applicable
predictor for customer retention (Gustafsson et al. 2005).
6. A Review of AI Based Medical Assistant ChatbotChetan Bulla, Chinmay Parushetti, Akshata
Teli, Samiksha Aski, Sachin Koppad
This is now the age of smart computer. Machines have started to impersonate as human, with the advent
of artificial intelligence, machine learning, and deep learning. Chatbot is classified as conversational
software agents enabled by natural language processing, and is an excellent example of such system. A
Chatbot is a program which allows the user to start a conversation with the machine. This is a platform
focused on Artificial Intelligence (AI),which can be developed as messaging applications, web
applications, or smartphone applications. A chatbot represents machine that answers questions using
Natural Language Processing (NLP). Formulating natural language answers to the questions. Chatbots
create a difference in the world of nursing and provide a simple way to handle people from professional
organizations. Health chatbots are capable of running one-on-one patient communications and of
reviewing specific patient queries. This program aims to investigate the existing e healthcare structure
involving a complex interaction with human machines and proposes an alternate method: a chat
interface designed and configured to act and interact with patients like a human being.
Chapter 3. System Design

3.1. Natural Language Processing (NLP)


Natural language processing (NLP) refers to the branch of computer science—and more specifically,
the branch of artificial intelligence or AI—concerned with giving computers the ability to understand
text and spoken words in much the same way human beings can. NLP combines computational
linguistics—rule-based modeling of human language—with statistical, machine learning, and deep
learning models. Together, these technologies enable computers to process human language in the form
of text or voice data and to ‘understand’ its full meaning, complete with the speaker or writer’s intent and
sentiment.
Natural language processing strives to build machines that understand and respond to text or voice
data—and respond with text or speech of their own—in much the same way humans do.

Python And Spacy


Python and spaCy complement each other seamlessly, as spaCy is a powerful natural language
processing library for Python. With spaCy, developers can perform various text processing tasks
efficiently, including tokenization, part-of-speech tagging, named entity recognition, and dependency
parsing. Its ease of use and high performance make it a preferred choice for many NLP projects and
applications. Additionally, spaCy offers pre-trained models and pipelines, enabling rapid development
and deployment of NLP solutions in Python environments.

3.2 Advantages of Natural Language Processing


⚫ The accuracy of the answer increases with the amount of relevant information provided in the
questions.
⚫ Structuring a high unstructured data source.
⚫ Users can ask questions about any subject and get a direct response in seconds.
⚫ It is easy to implement.
⚫ Using a program is less costly than hiring a person. A person can take two or three times longer than
a machine to execute the tasks mentioned.
⚫ NLP system provides answers to the questions in natural language.
⚫ Allow you to perform more language-based data compares to a human being without fatigue and in
an unbiased and consistent way.
⚫ NLP process help computer communicate with a human in their language and scales other
language-related tasks.
⚫ It is a faster customer service response time.

3.3. Disadvantage of Natural Language Processing


⚫ If it is necessary to develop a model with a new one without using a pre-trained model, it can take a
week to achieve a good performance depending o the amount of data.
⚫ The system is built for a single and specific task only, it is unable to adapt to new domains and
problems because of limited functions.
⚫ In complex query language, the system may not be able to provide the correct answer it a question
that is poorly worded or ambiguous.
⚫ It is not 100% reliable, It is never 100% dependable. There is the possibility of error in its prediction
and results.
3.4. Architecture Diagram

WEB PAGE

ANALYSIS REQU
CHATBOT EST USER

RESPONS
E

Fig 3.1. ARCHITECTURE DIAGRAM

3.5. Hardware Requirements


⚫ Modern Operating System
Windows 7 or 10
Mac OS X 10.11 or higher, 64-bit
Linux: RHEL 6/7, 64-bit
⚫ X86 64-bit CPU
⚫ 32 GB RAM
⚫ 3 GB Storage3.6. Software Requirements
⚫ Programming Language - Python 3.917

3.6. Software Requirement

⚫ Programming Language - Python 3.9or 3.12

⚫ IDE -Python

⚫ Spacy module

⚫ Tensorflow module

Conclusion-

In this chapter ,we have discussed introduction to NLP, software requirement,and


hardware requirement of the chatbot project and in next chapter ,we discuss about various
libraries used for creation of project in Python.
CHAPTER 4. ANALYSIS

4.1. PYTHON LIBRARY

A Python library is a collection of related modules. It contains bundles of code that can be used
repeatedly in different programs. It makes Python Programming simpler and convenient for the
programmer. As we don’t need to write the same code again and again for different programs. Python
libraries play a very vital role in fields of Machine Learning, Data Science,Data Visualization, etc.

Python libraries that are used in the project are:


⚫ Spacy
⚫ Tensorflow
⚫ Numpy
⚫ Random
⚫ Pickle

Spacy
SpaCy is a robust and efficient natural language processing (NLP) library for Python. It provides tools
and functionalities for various NLP tasks such as tokenization, part-of-speech tagging, named entity
recognition, dependency parsing, and more. spaCy is known for its speed and accuracy, making it a
popular choice for NLP practitioners and researchers alike. Additionally, SpaCy offers pre-trained
models and pipelines, allowing users to quickly get started with NLP tasks without the need for
extensive training data or model building. Overall, spaCy is a valuable tool for anyone working with text
data in Python.

Tensorflow
TensorFlow is a high-performance numerical calculation library that is open source. It is also employed
in deep learning algorithms and machine learning algorithms. It was created by the Google Brain team
researchers within the Google AI organization and is currently widely utilized by math, physics, and
machine learning researchers for complicated mathematical computations. TensorFlow is designed to be
fast, and it employs techniques such as XLA(XLA or Accelerated Linear Algebra is a domain-specific
compiler for linear algebra that can accelerate TensorFlow models with potentially no source code
changes.) to do speedy linear algebra computations.

Numpy
NumPy is one of the most widely used open-source Python libraries, focusing on scientific
computation. It features built-in mathematical functions for quick computation and supports big matrices
and multidimensional data. “Numerical Python” is defined by the term“NumPy.” It can be used in linear
algebra, as a multi-dimensional container for generic data,and as a random number generator, among
other things. Some of the important functions in NumPy are arcsin(), arccos(), tan(), radians(), etc.
NumPy Array is a Python object which defines an N-dimensional array with rows and columns. In
Python, NumPy Array is preferred over lists because it takes up less memory and is faster and more
convenient to use.

Random

Python Random module is an in-built module of Python which is used to generate random numbers.
These are pseudo-random numbers means these are not truly random. This module can be used to
perform random actions such as generating random numbers, print random a value for a list or string,
etc.

Pickle
Pickle in Python is primarily used in serializing and deserializing a Python object structure.In other
words, it’s the process of converting a Python object into a byte stream to store it in a file/database,
maintain program state across sessions, or transport data over the network. The pickled byte stream can
be used to re-create the original object hierarchy by unpickling the stream.

4.2. Data

The crucial element in artificial intelligence tasks is the data. The results will be highly influenced by the
data that are given, how are they formatted, their consistency, their relevance to the subject at hand and
so on. At this step, many questions should be answered in order to guarantee that the results will be
accurate and relevant. The data that is used should be clearly stated, in this case, with proper patterns
and responses.

4.3. Software Description

4.3.1. Python

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its
high-level built in data structures, combined with dynamic typing and dynamic binding, make it very
attractive for Rapid Application Development, as well as for use as a scripting or glue language to
connect existing components together. Python's simple, easy to learn syntax emphasizes readability and
therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse. The
Python interpreter and the extensive standard library are available in source or binary form without
charge for all major platforms, and can be freely distributed.
Python is the simplest language of all the programming languages, and in reality, is one-fifth when
compared with other OOP languages. This is why it is currently among the most well-known languages
in the marketplace.
Python comes with Prebuilt Libraries such as Numpy to perform scientific calculations, Scipy for
advanced computing, and Pybrain for machine learning (Python Machine Learning),making it among
the top languages for AI.
Python developers all over the globe offer extensive support and assistance through tutorials and forums,
helping the programmer much easier than another popular language.Python is platform-independent and
therefore is among the most adaptable and well-known options for various platforms and technologies,
with minimal modifications to the basics of coding.
Python has the greatest flexibility among other programs, with the option of choosing among OOPs
method and scripting. Additionally, you can use the IDE to search for all codes and blessing to
developers struggling with different algorithms.
4.3.2. Google Colab (Jupyter Notebook)
Google Colab is a cloud-based platform that allows users to write and execute Python code in a browser-
based environment known as a Jupyter notebook. It's based on Google's Jupyter Notebooks, and it
provides free access to computing resources such as GPU and TPU accelerators, making it popular
among data scientists, researchers, and students. With Google Colab, users can collaborate in real-time,
share their work easily, and leverage Google's infrastructure to run code efficiently without worrying
about hardware constraints. Additionally, Colab supports various libraries and frameworks commonly
used in data science and machine learning, making it a convenient choice for prototyping,
experimenting, and even deploying machine learning models.

Conclusion-
In this chapter we have discussed various library used for creation of chatbot and in next chapter ,we see
how to create a chatbot step by step.
CHAPTER 5. HOW TO CREATE A CHABOT IN PYTHON

5.1. FILES STRUCTURE

Now we are going to build the chatbot using Python but first, let us see the file structure and the type of
files we will be creating:
Intents.json – The data file which has predefined patterns and responses.
Words.pkl – This is a pickle file in which we store the words Python object that contains a list of our
vocabulary.
Classes.pkl – The classes pickle file contains the list of categories.
Chatbot_model.h5 – This is the trained model that contains information about the model and has weights
of the neurons.
Chatbot.ipynb– This is the jupyter file in which we implemented GUI for our chatbot. Users can easily
interact with the bot.or python script for simple chatbot creation in google colab.

5.2. STEPS TO CREATE CHATBOT IN PYTHON

Here are the 5 steps to create a chatbot in Python from scratch-


⚫ Import and load the data file
⚫ Preprocess data
⚫ Create training and testing data
⚫ Build the model
⚫ Predict the response

1. Import and load the data file

First, make a file name training.py. We import the necessary packages for our chatbot and initialize the
variables we will use in our Python project.
2. Preprocess data
When working with text data, we need to perform various preprocessing on the data before we make a
machine learning or a deep learning model. Based on the requirements we need to apply various
operations to preprocess the data.

Tokenizing is the most basic and first thing you can do on text data. Tokenizing is the process of
breaking the whole text into small parts like words.

Here we iterate through the patterns and tokenize the sentence using nltk.word_tokenize() function and
append each word in the words list. We also create a list of classes for our tags.

3. Create training and testing data


Now, we will create the training data in which we will provide the input and the output. Our input will
be the pattern and output will be the class our input pattern belongs to. But the computer doesn’t
understand text so we will convert text into numbers.

4. Build the model


We have our training data ready, now we will build a deep neural network that has 3 layers. We use the
Keras sequential API for this. After training the model for 200 epochs, we achieved 100% accuracy on
our model. Let us save the model as ‘chatbot_model.h5’.

5. Predict the response (Graphical User Interface)


To predict the sentences and get a response from the user to let us create a new file ‘chatbot.ipynb'.
We will load the trained model and then use a graphical user interface that will predict the response from
the bot. The model will only tell us the class it belongs to, so we will implement some functions which
will identify the class and then retrieve us a random response from the list of responses.

Again we import the necessary packages and load the ‘words.pkl’ and ‘classes.pkl’ pickle files which we
have created when we trained our model.
To predict the class, we will need to provide input in the same way as we did while training. So we will
create some functions that will perform text preprocessing and then predict the class.
After predicting the class, we will get a random response from the list of intents.

Now we will develop a graphical user interface. Let’s use Gradio library which is shipped with tons of
useful libraries for GUI. We will take the input message from the user and then use the helper functions
we have created to get the response from the bot and display it on the GUI.

6. Run the chatbot

To run the chatbot, we have two main files; training.py and chatbot.py
First, we train the model using the command in the terminal:

python train_chatbot.py
If we don’t see any error during training, we have successfully created the model. Then to run the app,
we run the second file.

python chatbot.py
The program will open up a GUI window within a few seconds. With the GUI you can easily chat with
the bot.
Fig 5.1. Sample Output
CHAPTER 6. IMPLEMENTION OF CODE

6.1. TRAINING DATA AND CREATING CHATBOT CODE


#chatbot.ipynb

# Install necessary libraries


!pip install tensorflow==2.7.0
!pip install gradio

import spacy
import numpy as np
import random
import pickle
import gradio as gr
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import SGD
import json

# Initialize spaCy
nlp = spacy.load('en_core_web_sm')

def tokenize(text):
"""Tokenize the input text."""
return [token.text for token in nlp(text)]

def lemmatize(word):
"""Lemmatize the input word."""
return nlp(word)[0].lemma_
# Define intents directly in the script (including Hinglish patterns)
intents = {
"intents": [
{
"tag": "greeting",
"patterns": [
"Hi",
"Hello",
"How are you?",
"Good morning",
"Good evening",
"Namaste",
"Kaise ho?"
],
"responses": [
"Hello! How can I assist you today?",
"Hi there! How can I help?",
"Greetings! How can I support you?",
"Namaste! Aapko kaise madad kar sakta hoon?"
],
"context_set": "ask_name"
},
{
"tag": "ask_name",
"patterns": [
""
],
"responses": [
"Before we start, may I know your name?"
]
},
{
"tag": "name_provided",
"patterns": [
""
],
"responses": [
"Nice to meet you {name}!",
"Hello {name}! How can I assist you today?",
"Hi {name}! What can I do for you?"
]
},
{
"tag": "goodbye",
"patterns": [
"Bye",
"See you later",
"Goodbye",
"Catch you later",
"Alvida",
"Phir milenge"
],
"responses": [
"Goodbye!",
"See you later!",
"Take care!",
"Alvida!",
"Phir milenge!"
]
},
{
"tag": "thanks",
"patterns": [
"Thanks",
"Thank you",
"That's helpful",
"I appreciate it",
"Shukriya",
"Dhanyavaad"
],
"responses": [
"You're welcome!",
"No problem!",
"My pleasure!",
"Shukriya!",
"Koi baat nahi!"
]
},
{
"tag": "noanswer",
"patterns": [
"",
"What does this bot do?",
"Help",
"Can you assist me?",
"Yeh bot kya karta hai?",
"Madad kar sakte ho?"
],
"responses": [
"I'm here to help you!",
"What can I do for you?",
"Main aapki madad ke liye hoon!",
"Main yahan aapki madad karne ke liye hoon!"
]
},
{
"tag": "age",
"patterns": [
"How old are you?",
"What's your age?",
"Tell me your age",
"Aapki umar kya hai?"
],
"responses": [
"I don't have an age.",
"I'm ageless!",
"Meri koi umar nahi hai.",
"Main bina umar ka hoon."
]
},
{
"tag": "name",
"patterns": [
"What is your name?",
"Who are you?",
"Tell me your name",
"Aapka naam kya hai?"
],
"responses": [
"I'm a chatbot.",
"I don't have a name.",
"Main ek chatbot hoon.",
"Mera koi naam nahi hai."
]
},
{
"tag": "shop",
"patterns": [
"I'd like to buy something",
"Show me the shop",
"What do you sell?",
"Mujhe kuch khareedna hai",
"Dukaan dikhao"
],
"responses": [
"We sell various products.",
"Check out our store!",
"Hum alag-alag cheezein bechte hain.",
"Hamare store mein dekho!"
]
},
{
"tag": "hours",
"patterns": [
"What are your hours?",
"When are you open?",
"What is your opening time?",
"Aap kab khulte ho?"
],
"responses": [
"We are open 24/7!",
"Our hours are 9am to 9pm.",
"Hum 24/7 khule hain.",
"Hum 24 ghante, 7 din khule hain."
]
},
{
"tag": "payments",
"patterns": [
"Do you take credit cards?",
"Can I pay with PayPal?",
"Do you accept Visa?",
"Kya aap credit card lete hain?",
"Main PayPal se pay kar sakta hoon?"
],
"responses": [
"We accept all major credit cards.",
"PayPal is accepted.",
"Hum sabhi pramukh credit cards lete hain.",
"Hum PayPal bhi accept karte hain."
]
},
{
"tag": "location",
"patterns": [
"Where are you located?",
"What is your address?",
"How do I find you?",
"Aap kaha ho?"
],
"responses": [
"We are located online.",
"Our address is on our website.",
"Hum online maujood hain.",
"Hamari address website par hai."
]
},
{
"tag": "food",
"patterns": [
"Can you have a cup of tea with me?",
"Can we have chai together?",
"Let's grab a coffee.",
"Chai piyoge mere saath?"
],
"responses": [
"Sure, I'd love to!",
"That sounds great!",
"Of course!",
"Zaroor, mujhe bhi!"
]
},
{
"tag": "general_knowledge",
"patterns": [
"What is the capital of India?",
"Who wrote Harry Potter?",
"What is the currency of Japan?",
"Name the largest continent.",
"Who painted the Mona Lisa?"
],
"responses": [
"The capital of India is New Delhi.",
"Harry Potter was written by J.K. Rowling.",
"The currency of Japan is the Japanese Yen (JPY).",
"Asia is the largest continent.",
"The Mona Lisa was painted by Leonardo da Vinci."
]
},
{
"tag": "chatbot_details",
"patterns": [
"Tell me about yourself",
"Who created you?",
"What can you do?",
"Aap ke baare mein batao",
"Kaun ne aapko banaya hai?"
],
"responses": [
"I am a chatbot created to assist you with information and tasks.",
"I was created by developers to help users like you.",
"I can answer your questions, provide information, and assist with
tasks.",
"Main ek chatbot hoon jo aapko jaankari aur karyo mein madad
karne ke liye bana gaya hai."
]
}
]
}

# Preprocess the data


words = []
classes = []
documents = []
ignore_words = ['?', '!', '.', ',']

for intent in intents['intents']:


for pattern in intent['patterns']:
w = tokenize(pattern)
words.extend(w)
documents.append((w, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])

words = [lemmatize(w.lower()) for w in words if w not in ignore_words]


words = sorted(list(set(words)))
classes = sorted(list(set(classes)))

print(len(documents), "documents")
print(len(classes), "classes", classes)
print(len(words), "unique lemmatized words", words)

# Training data preparation


training = []
output_empty = [0] * len(classes)

for doc in documents:


bag = []
pattern_words = doc[0]
pattern_words = [lemmatize(word.lower()) for word in pattern_words]
for w in words:
bag.append(1) if w in pattern_words else bag.append(0)
output_row = list(output_empty)
output_row[classes.index(doc[1])] = 1
training.append([bag, output_row])

random.shuffle(training)
training = np.array(training, dtype=object)
train_x = np.array(list(training[:, 0]))
train_y = np.array(list(training[:, 1]))

print("Training data created")

# Model building
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))

# Compile model
sgd = SGD(learning_rate=0.01, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd,
metrics=['accuracy'])

# Train the model


hist = model.fit(train_x, train_y, epochs=200, batch_size=5, verbose=1)

# Save the model


model.save('chatbot_model.h5')

# Save words and classes


pickle.dump(words, open('words.pkl', 'wb'))
pickle.dump(classes, open('classes.pkl', 'wb'))

print("Model created")
# Load model and data for inference
from tensorflow.keras.models import load_model
model = load_model('chatbot_model.h5')
words = pickle.load(open('words.pkl', 'rb'))
classes = pickle.load(open('classes.pkl', 'rb'))

def clean_up_sentence(sentence):
sentence_words = tokenize(sentence)
sentence_words = [lemmatize(word.lower()) for word in sentence_words]
return sentence_words

def bow(sentence, words, show_details=True):


sentence_words = clean_up_sentence(sentence)
bag = [0]*len(words)
for s in sentence_words:
for i, w in enumerate(words):
if w == s:
bag[i] = 1
if show_details:
print(f"found in bag: {w}")
return(np.array(bag))

def classify_local(sentence):
ERROR_THRESHOLD = 0.25
input_data = np.array([bow(sentence, words)], dtype=float)
results = model.predict(input_data)[0]
results = [[i, r] for i, r in enumerate(results) if r >
ERROR_THRESHOLD]
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
return_list.append((classes[r[0]], str(r[1])))
return return_list

def response(sentence, chat_history):


results = classify_local(sentence)
if results:
for i in intents['intents']:
if i['tag'] == results[0][0]:
response = random.choice(i['responses'])
chat_history.append(("Bot", response))
return response, chat_history
response = "I didn't understand that. Can you please rephrase?"
chat_history.append(("Bot", response))
return response, chat_history

# Gradio interface with chat history


def chatbot_interface(message, chat_history):
if chat_history is None:
chat_history = []
chat_history.append(("User", message))
response_message, chat_history = response(message, chat_history)
return chat_history, chat_history

iface = gr.Interface(
fn=chatbot_interface,
inputs=["text", "state"],
outputs=["chatbot", "state"],
title="Hinglish Chatbot",
description="A chatbot that understands Hinglish"
)
iface.launch()
6.1.0 OUTPUT OF chatbot.ipynb

SAMPLE OUTPUT-1

Fig 6.1.1 Chatbot.ipynb Output 1


SAMPLE OUTPUT-2

Fig 6.1.2 Chatbot.ipynb Output 2


SAMPLE OUTPUT 3

Fig6.1.3 Chatbot.ipynb Output 3


SAMPLE OUTPUT 4

Fig 6.1.4. Chatbot.ipynb Output 4


SAMPLE OUTPUT 5

Fig 6.1.5 Chatbot.ipynb Output 5


CONCLUSION

A chat-bot is one of the easiest way to fetch information from a system without having to think for
proper keywords to lookup in a search engine or browse several web pages to collect information users
can easily type their query in natural language and retrieve information. This project looks into how
the chat-bot can be tailored to be used as a domain specific chat-bot, and how can this application make
the procedure of hotel booking user-friendly for the android users. Existing chat-bots have various
missing aspects that is covered by this system, making it superior.This chat-bot has built-in knowledge-
base, conversational abilities, real-time support, and human visual look. It can act as a great virtual
assistant for hotel booking and can perform multi-dimensional evaluation. Android based smart chat-bot
is a very promising system and aims to enhance the user and customer experience.
REFERENCES

1. Chatbot Development Using Python by Shreyashkar Sharma from School Of Computing Science
And Engineering, Galgotias University, Greater Noida https://ijcrt.org/papers/IJCRT2007585.pdf.

2.Development Of Chatterbot Using Python by P. Shanmugapriya, and Harini M


https://www.ijcaonline.org/archives/volume176/number21/shanmugapriya-2020-ijca-920184.pdf.

3.Python Chatbot Project – Learn To Build Your First Chatbot Using NLTK & Keras by Isaac
Ikwuegbu from IU International University of Applied Sciences
https://www.researchgate.net/publication/35821494828

4. An Overview of Chatbot Technology - Eleni Adamopoulou and Lefteris Moussiades.2020. An


Overview of Chatbot Technology. An Overview of Chatbot Technology |SpringerLink. Retrieved
November 28, 2022 from
https://link.springer.com/chapter/10.1007/978-3-030-49186-4_31

5.AI-based Chatbot Service for Financial Industry - Takuma Okuda , Sanae Shoda

6.Rule-Based Chatbot Integration into Software Engineering Course Binkis, Mikas, etal. “Rule-Based
Chatbot Integration Into Software Engineering Course.” Rule-Based Chatbot Integration Into Software
Engineering Course | SpringerLink, 7 Oct. 2021,link.springer.com/chapter/10.1007/978-3-030-88304-
1_29.7.

7.An overview of artificial intelligence based chatbots and an example chatbot application - N.
Albayrak, A. Özdemir and E. Zeydan, "An overview of artificial intelligence based chatbots and an
example chatbot application," 2018 26th Signal Processing and Communications Applications
Conference (SIU), 2018, pp. 1-4, doi:10.1109/SIU.2018.8404430.8.

8.AI-based chatbots in customer service and their effects on user compliance - Adam,Martin, et al. “AI-
based Chatbots in Customer Service and Their Effects on User Compliance - Electronic Markets.”
SpringerLink, 17 Mar. 2020,link.springer.com/article/10.1007/s12525-020-00414-7.

9.A Review of AI Based Medical Assistant Chatbot - Chetan Bulla, Chinmay Parushetti, Akshata Teli,
Samiksha Aski, Sachin Koppad

10. An intelligent knowledge-based chatbot for customer service Eric W.T. Ngai, Maggie C.M. Lee, Mei
Luo, Patrick S.L Eric W.T. Ngai, Maggie C.M. Lee, Mei Luo, Patrick S.L. Chan, Tenglu Liang,An
intelligent knowledge-based chatbot for customer service,https://doi.org/10.1016/j.elerap.2021.101098.
( https://www.sciencedirect.com/science/article/pii/S1567422321000703)

11. Application of AI based Chatbot Technology in the Industry – Park, Arum; Lee, SaeBom ; Song
Jaemin.

You might also like