Building a Rule-based Chatbot in Python


Chatbots have develop into extraordinarily in style lately and their use within the trade has skyrocketed. They’ve discovered a robust foothold in virtually each job that requires text-based public dealing. They’ve develop into so vital within the help trade, for instance, that just about 25% of all customer support operations are anticipated to make use of them by 2020.

Within the first part of A Beginners Guide to Chatbots, we mentioned what chatbots have been, their rise to reputation and their use-cases within the trade. We additionally noticed how the expertise has advanced over the previous 50 years.

On this second a part of the collection, we’ll be taking you thru the right way to construct a easy Rule-based chatbot in Python. Earlier than we begin with the tutorial, we have to perceive the several types of chatbots and the way they work.

Varieties of Chatbots

Chatbots could be categorized into two differing types, primarily based on how they’re constructed:

Rule-Primarily based Chatbots

Rule-based chatbots are fairly straight ahead. They’re supplied with a database of responses and are given a algorithm that assist them match out an acceptable response from the offered database. They can not generate their very own solutions however with an intensive database of solutions and neatly designed guidelines, they are often very productive and helpful.

The only type of Rule-based Chatbots have one-to-one tables of inputs and their responses. These bots are extraordinarily restricted and may solely reply to queries if they’re an actual match with the inputs outlined of their database.

AI-Primarily based Chatbots

With the rise in the usage of machine studying lately, a brand new method to constructing chatbots has emerged. Utilizing synthetic intelligence, it has develop into doable to create extraordinarily intuitive and exact chatbots tailor-made to particular functions.

Not like their rule-based kin, AI primarily based chatbots are primarily based on advanced machine studying fashions that allow them to self-learn.

Now that we’re conversant in how chatbots work, we’ll be wanting on the libraries that can be used to construct our easy Rule-based Chatbot.

Pure Language Toolkit is a Python library that makes it straightforward to course of human language information. It supplies easy-to-use interfaces to many language-based assets such because the Open Multilingual Wordnet, in addition to entry to a wide range of text-processing libraries.

Common Expression (RegEx) in Python

A common expression is a particular sequence of characters that helps you seek for and discover patterns of phrases/sentences/sequence of letters in units of strings, utilizing a specialised syntax. They’re broadly used for textual content looking and matching in UNIX.

Python contains help for normal expression by means of the re package deal.

Need to improve your Python skills? Checkout Information Science Dojo’s Introduction to Python for Data Science.

Constructing a Chatbot

This quite simple rule primarily based chatbot will work by looking for particular key phrases in inputs given by a consumer. The key phrases can be used to grasp what motion the consumer needs to take (consumer’s intent). As soon as the intent is recognized, the bot will then select a response acceptable to the intent.

The checklist of key phrases the bot can be looking for and the dictionary of responses can be constructed up manually primarily based on the particular use case for the chatbot.

We’ll be designing a quite simple chatbot for a Financial institution. The bot will be capable of reply to greetings (Hello, Whats up and so forth.) and can be capable of reply questions in regards to the financial institution’s hours of operation.

A movement of how the chatbot would course of inputs is proven beneath;

We can be following the steps beneath to construct our chatbot

  1. Importing Dependencies
  2. Constructing the Key phrase Checklist
  3. Constructing a dictionary of Intents
  4. Defining a dictionary of responses
  5. Matching Intents and Producing Responses

Importing Dependencies

The very first thing we’ll have to do is import the packages/libraries we’ll be utilizing. re is the package deal that handles common expression in Python. We’ll even be utilizing WordNet from NLTK. WordNet is a lexical database that defines semantical relationships between phrases. We’ll be utilizing WordNet to construct up a dictionary of synonyms to our key phrases. It will assist us develop our checklist of key phrases with out manually having to introduce each doable phrase a consumer may use.

# Importing modules
import re
from nltk.corpus import wordnet

Constructing a Checklist of Key phrases

As soon as we now have imported our libraries, we’ll have to construct up a listing of key phrases that our chatbot will search for. This checklist could be as exhaustive as you need. The extra key phrases you’ve gotten, the higher your chatbot will carry out.

As mentioned beforehand, we’ll be utilizing WordNet to construct up a dictionary of synonyms to our key phrases. For particulars about how WordNet is structured, visit their website.


# Constructing a listing of Key phrases
for phrase in list_words:
    for syn in wordnet.synsets(phrase):
        for lem in syn.lemmas():
            # Take away any particular characters from synonym strings
            lem_name = re.sub('[^a-zA-Z0-9 n.]', ' ', lem.title())
print (list_syn)


good day
{'good day', 'howdy', 'hello', 'hullo', 'how do you do'}
{'time', 'clock', 'timing'}

Right here, we first outlined a listing of phrases list_words that we are going to be utilizing as our key phrases. We used WordNet to develop our preliminary checklist with synonyms of the key phrases. This checklist of key phrases is saved in list_syn.

New key phrases can merely be added to list_words. The chatbot will robotically pull their synonyms and add them to the key phrases dictionary. You can too edit list_syn immediately if you wish to add particular phrases or phrases that you recognize your customers will use.

Constructing a Dictionary of Intents

As soon as our key phrases checklist is full, we’d like construct up a dictionary that matches our key phrases to intents. We additionally have to reformat the key phrases in a particular syntax that makes them seen to Regular Expression’s search function.


# Constructing dictionary of Intents & Key phrases
key phrases={}

# Defining a brand new key within the key phrases dictionary
key phrases['greet']=[]

# Populating the values within the key phrases dictionary with synonyms of key phrases formatted with RegEx metacharacters 
for synonym in checklist(list_syn['hello']):
    key phrases['greet'].append('.*b'+synonym+'b.*')
# Defining a brand new key within the key phrases dictionary
key phrases['timings']=[]

# Populating the values within the key phrases dictionary with synonyms of key phrases formatted with RegEx metacharacters 
for synonym in checklist(list_syn['timings']):
    key phrases['timings'].append('.*b'+synonym+'b.*')
for intent, keys in key phrases.gadgets():
    # Becoming a member of the values within the key phrases dictionary with the OR (|) operator updating them in keywords_dict dictionary
    keywords_dict[intent]=re.compile('|'.be part of(keys))
print (keywords_dict)



The up to date and formatted dictionary is saved in keywords_dict. The intent is the important thing and the string of key phrases is the worth of the dictionary.  

Let’s take a look at one key-value pair of the keywords_dict dictionary to grasp the syntax of Common Expression;

{'greet': re.compile('.*bhullob.*|.*bhow-do-you-dob.*|.*bhowdyb.*|.*bhellob.*|.*bhib.*')

Common Expression makes use of particular patterns of particular Meta-Characters to seek for strings or units of strings in an expression.

Since we’d like our chatbot to seek for particular phrases in bigger enter strings we use the next sequences of meta-characters:


On this particular sequence, the key phrase (hullo) is encased between a b sequence. This tells the RegEx Search function that the search parameter is the key phrase (hullo).

The primary sequence bhullob is encased between a period-star .* sequence. This sequence tells the RegEx Search function to look your complete enter string from starting to finish for the search parameter (hullo).

Within the dictionary, a number of such sequences are separated by the OR | operator. This operator tells the search operate to search for any of the talked about key phrases within the enter string.

Extra particulars about Common Expression and its syntax could be discovered here.

You possibly can add as many key-value pairs to the dictionary as you wish to improve the performance of the chatbot.

Defining Responses

The following step is defining responses for every intent kind. This half could be very simple. The responses are described in one other dictionary with the intent being the important thing.

We’ve additionally added a fallback intent and its response. It is a fail-safe response in case the chatbot is unable to extract any related key phrases from the consumer enter.


# Constructing a dictionary of responses
    'greet':'Whats up! How can I enable you?',
    'timings':'We're open from 9AM to 5PM, Monday to Friday. We're closed on weekends and public holidays.',
    'fallback':'I dont fairly perceive. Might you repeat that?',

Matching Intents and Producing Responses

Now that we now have the back-end of the chatbot accomplished, we’ll transfer on to taking an enter from the consumer and looking the enter string for our key phrases.

We use the RegEx Search function to look the consumer enter for key phrases saved within the worth subject of the keywords_dict dictionary.  If you happen to recall, the values within the keywords_dict dictionary have been formatted with particular sequences of meta-characters. RegEx’s search operate makes use of these sequences to check the patterns of characters within the key phrases with patterns of characters within the enter string.

If a match is discovered, the present intent will get chosen and is used as the important thing to the responses dictionary to pick out the right response.


print ("Welcome to MyBank. How could I enable you?")

# Whereas loop to run the chatbot indefinetely
whereas (True):  
    # Takes the consumer enter and converts all characters to lowercase
    user_input = enter().decrease()
    # Defining the Chatbot's exit situation
    if user_input == 'give up': 
        print ("Thanks for visiting.")
    matched_intent = None 
    for intent,sample in keywords_dict.gadgets():
        # Utilizing the common expression search operate to search for key phrases in consumer enter
        if, user_input): 
            # if a key phrase matches, choose the corresponding intent from the keywords_dict dictionary
    # The fallback intent is chosen by default
    if matched_intent in responses:
        # If a key phrase matches, the fallback intent is changed by the matched intent as the important thing for the responses dictionary
        key = matched_intent 
    # The chatbot prints the response that matches the chosen intent
    print (responses[key]) 

Pattern dialog with Bankbot:

The chatbot picked the greeting from the primary consumer enter (‘Hello’) and responded in accordance with the matched intent. The identical occurred when it situated the phrase (‘time’) within the second consumer enter. The third consumer enter (‘How can I open a checking account’) didn’t have any key phrases that current in Bankbot’s database and so it went to its fallback intent.

You possibly can add as many key phrases/phrases/sentences and intents as you wish to make certain your chatbot is strong when speaking to an precise human.


This weblog was a hands-on introduction to constructing a quite simple rule-based chatbot in python. We solely labored with 2 intents on this tutorial for simplicity. You possibly can simply develop the performance of this chatbot by including extra key phrases, intents and responses.

As we noticed, constructing a rule-based chatbot is a laborious course of. In a enterprise setting, a chatbot might be required to have much more intents relying on the duties it’s purported to undertake.

In such a state of affairs, rule-based chatbots develop into very impractical as sustaining a rule base would develop into extraordinarily advanced. As well as, the chatbot would severely be restricted by way of its conversational capabilities as it’s close to inconceivable to explain precisely how a consumer will work together with the bot.

AI-based Chatbots are a way more sensible answer for real-world situations. Within the subsequent weblog within the collection, we’ll be taking a look at the right way to construct a easy AI-based Chatbot in Python.

Do you wish to study extra about machine studying and it is functions? Take a look at Information Science Dojo’s online data science certificate program!


Source link

Write a comment