Building your own Rule-Based Conversational Chatbot | Python Implementation

Lakshmi Panneerselvam 15 Jun, 2021 • 5 min read

This article was published as a part of the Data Science Blogathon

Let’s have a really quick intro about chatbots and it’s major aspects!

chatbot Image

A Chatbot is a software application used to conduct an on-line chat conversation via text or text-to-speech, in lieu of providing direct contact with a live human agent. Chatbot, short for chatterbot, is an artificial intelligence (AI)
feature that can be embedded and used through any major messaging applications – Wikipedia.

Why is it important?

CHATBOT CONVERSATIONAL AGENT VIRTUAL ASSISTANT
Operates on a single-turn exchange basis. Engages user in conversation to understand the nature of the problem. A conversational agent is trained to ask a set of questions that can pinpoint the problem and potentially solve it. Answers improve over time as virtual assistant learns more about the user.

The chatbots are programs that could simulate the conversation of a human through voice or text interactions. These bots are increasingly being used in both B2B and B2C (Business-to-Business & Business-to-Consumer) to handle various look-up tasks.

Pros & Cons

The benefits of using a chatbot for varied purposes include the following properties:

  • Effective cost
  • Focus on time-saving
  • Proactive interaction with users

Furthermore, the chatbots face various challenges like:

  • It cannot understand and adapt with the spontaneity of a human since its behavior is controlled by varying emotions. For example, the user might give a command initially and then switch to asking for a suggestion.
  • Since the NLP in a chatbot might be limited, when a user tends to use different slang, or an acronym, or even misspell certain words, it finds it difficult to understand and resolve this type of challenge.

How does it work?

These bots are built on AI technologies, along with NLP, machine learning, deep learning algorithms, and would require massive amounts of data. Selecting the right NLP engine is being the most important aspect of implementing a chatbot. They are said to have varying levels of complexity since the owners have to decide whether they are in need of structured conversations or unstructured ones.

The working process might look simple yet seems to be quite complex in practice:

  • The user gives a request to the bot
  • Bot analyzes user’s request to identify the intent of the user
  • Extracts relevant entities based on the intent
  • Provides the user with the most appropriate response

The Chatbots are classified into a number of types like scripted chatbots, hybrid chatbots, voice-enabled or contextual chatbots but then all of these tend to work in one of the two ways, either with set guidelines or via machine learning. The Rule-based bot is something that uses some of the other rules for its training purpose, whereas the Self-learning bot utilizes a machine-learning-based approach for the conversation.

This blog will explicate how to create a simple rule-based bot in the easiest way using python code.

NLTK chatbot

Step 1: Import the required Libraries

from nltk.chat.util import Chat, reflections

Step 2: Pattern-Response Pairs!

Create a list of recognizable patterns and an appropriate response to those patterns.

#create a variable named pairs
pairs = [
        r"(.*)my name is (.*)", #request
        ["Hello %2, How are you today ?",] #response
    ],
    [
        r"(.*)help(.*) ",
        ["I can help you ",]
    ],
     [
        r"(.*) your name ?",
        ["My name is beedo, but you can just call me robot and I'm a chatbot .",]
    ],
    [
        r"how are you (.*) ?",
        ["I'm doing very well", "i am great !"]
    ],
    [
        r"sorry (.*)",
        ["Its alright","Its OK, never mind that",]
    ],
    [
        r"i'm (.*) (good|well|okay|ok)",
        ["Nice to hear that","Alright, great !",]
    ],
    [
        r"(hi|hey|hello|hola|holla)(.*)",
        ["Hello", "Hey there",]
    ],
    [
        r"what (.*) want ?",
        ["Make me an offer I can't refuse",]
    ],
    [
        r"(.*)created(.*)",
        ["Aman Kharwal created me using Python's NLTK library ","top secret ;)",]
    ],
    [
        r"(.*) (location|city) ?",
        ['New Delhi, India',]
    ],
    [
        r"(.*)raining in (.*)",
        ["No rain in the past 4 days here in %2","In %2 there is a 50% chance of rain",]
    ],
    [
        r"how (.*) health (.*)",
        ["Health is very important, but I am a computer, so I don't need to worry about my health ",]
    ],
    [
        r"(.*)(sports|game|sport)(.*)",
        ["I'm a very big fan of Cricket",]
    ],
    [
        r"who (.*) (Cricketer|Batsman)?",
        ["Virat Kohli"]
    ],
    [
        r"quit",
        ["Bye for now. See you soon :) ","It was nice talking to you. See you soon :)"]
    ],
    [
        r"(.*)",
        ['That is nice to hear']
    ],
]

Step 3: Reflections

The very next step after creating the pattern and response pair is the Reflections. Reflections are nothing but a dictionary file that consists of a set of input values and their corresponding output values. For
For example, if your input string is “I am an Engineer”, then the output would be
“You are an Engineer”.

print(reflections)

Output:

{‘i am’: ‘you are’, ‘i was’: ‘you were’, ‘i’: ‘you’, “i’m”: ‘you are’, “i’d”: ‘you would’, “i’ve”: ‘you have’, “i’ll”: ‘you will’, ‘my’: ‘your’, ‘you are’: ‘I am’, ‘you were’: ‘I was’, “you’ve”: ‘I have’, “you’ll”: ‘I will’, ‘your’: ‘my’, ‘yours’: ‘mine’, ‘you’: ‘me’, ‘me’: ‘you’}

Note that, you can also create your own reflections dictionary in the same format as mentioned above.

For example,

dummy_reflections = { "go": "gone", "hello": "hey there" }

Step 4: The default message & Chatbot creation

Now it’s time to print a default message (to be printed at the start of your chat), and finish creating your chatbot.

print("Hi, I'm Beedo and I like to chat.nPlease type in English language (lowercase) to start a conversation. Type quit to leave. ")
chat = Chat(pairs, reflections)
Output:
Hi, I'm Beedo and I like to chat.
Please type in English language (lowercase) to start a conversation. Type quit to leave.

Step 5: Ta-da!
Have super fun conversing with your own talkbot! 😀

chat.converse()
Output:
>hi my name is lakshmi
Hello lakshmi, How are you today ?
>i am good
That is nice to hear
>what is your name?
My name is beedo, but you can just call me robot and I'm a chatbot .
>how are you beedo?
i am great !
>quit
It was nice talking to you. See you soon :)

End Notes

If you’re much interested to know what a chatbot actually is and exploring more about its functionalities, this blog would help you in a better way I suppose! Don’t just stop here, have a look at the few interesting resources I’ve added below and… get going 😉

“An Investment in knowledge pays the best interest,” says Benjamin Franklin.

Happy Learning Y’all :))

Resources

https://towardsdatascience.com/how-to-create-a-chatbot-with-python-deep-learning-in-less-than-an-hour-56a063bdfc44

https://www.upgrad.com/blog/how-to-make-chatbot-in-python/

https://www.kdnuggets.com/2019/12/build-intelligent-chatbot.html

https://www.netomi.com/best-ai-chatbot

https://research.aimultiple.com/top-chatbot-success/

About Me

I am Lakshmi Panneer, a product of the 90’s. I hold a Masters’s degree in Information Technology. Engineer by Profession. Blogger by Passion. I live in Chennai, TN. Over the years, I had been reading a lot of random stuff and write articles about it. Drop me a line anytime, whether it’s about feedback/suggestions, I’d really love hearing from you!

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Joao
Joao 02 Aug, 2021

Hi! I enjoyed your article and I tried to replicate it. Is the "pairs" structure right? Would it be an array with dictionary in each line? Something like bellow? If not, could you explain me that structure? pairs = [ { r"(.*)my name is (.*)": # request ["Hello %2, How are you today ?", ] # response} }, { r"(.*)help(.*) ": ["I can help you ", ] }, { r"(.*) your name ?": ["My name is beedo, but you can just call me robot and I'm a chatbot .", ] }, { r"how are you (.*) ?": ["I'm doing very well", "i am great !"] }, { r"i'm (.*) (good|well|okay|ok)": ["Nice to hear that", "Alright, great !", ] }, { r"(hi|hey|hello|hola|holla)(.*)": ["Hello", "Hey there", ] }, { r"what (.*) want ?": ["Make me an offer I can't refuse", ] }, { r"(.*)created(.*)": ["Aman Kharwal created me using Python's NLTK library ", "top secret ;)", ] }, { r"(.*) (location|city) ?": ['New Delhi, India', ] }, { r"(.*)raining in (.*)": ["No rain in the past 4 days here in %2", "In %2 there is a 50% chance of rain", ] }, { r"how (.*) health (.*)": ["Health is very important, but I am a computer, so I don't need to worry about my health ", ] }, { r"(.*)(sports|game|sport)(.*)": ["I'm a very big fan of Cricket", ] }, { r"who (.*) (Cricketer|Batsman)?": ["Virat Kohli"] }, { r"quit": ["Bye for now. See you soon :) ", "It was nice talking to you. See you soon :)"] }, { r"(.*)": ['That is nice to hear'] } ]

ELvira
ELvira 07 Apr, 2022

Hi Lakshmi, This article is so informative, I would love to chat more because of my current research interests, is this possible? thank you

Natural Language Processing
Become a full stack data scientist