Chatbot Project Report
Chatbot Project Report
Submitted in Partial Fulfillment of the Requirement for the Award of the Degree
of
BACHELOR OF TECHNOLOGY
IN
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
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.
Date:
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
1 Introduction 1
1.1.Overview of the Project
1.2.Scope and Objective
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
7 Conclusion 38
8 Reference 39-40
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.
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.
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.
WEB PAGE
ANALYSIS REQU
CHATBOT EST USER
RESPONS
E
⚫ IDE -Python
⚫ Spacy module
⚫ Tensorflow module
Conclusion-
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.
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.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
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.
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.
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.
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
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."
]
}
]
}
print(len(documents), "documents")
print(len(classes), "classes", classes)
print(len(words), "unique lemmatized words", words)
random.shuffle(training)
training = np.array(training, dtype=object)
train_x = np.array(list(training[:, 0]))
train_y = np.array(list(training[:, 1]))
# 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'])
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 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
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
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.
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
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.