On your local PC, a local chatbot that is completely offline and private

Andika Wirawan
12 min readAug 9, 2023

--

Chatbots are software applications that can interact with humans using natural language. Chatbots can be used for a variety of purposes, such as customer service, entertainment, education, or personal assistance. However, most chatbots require an internet connection and cloud-based services to work. This means that your data and privacy can be compromised when you use this chatbot.

If you want to build a chatbot that works on your local PC, without internet connection or cloud dependency, and with 100% privacy, then this article is for you. In this article, you will learn how to create a local chatbot using Python, a popular and versatile programming language. You’ll also learn how to use some of the best Python libraries and frameworks for building chatbots, such as ChatterBot, spaCy, and Rasa.

By the end of this article, you will have a fully functional local chatbot that can chat with you on various topics and perform some tasks for you.

Step 1: Install Python and required libraries on your PC

To build a local chatbot, you must have Python installed on your PC. Python is a free and open source programming language that has a large and active community of developers and users. Python is easy to learn and use, and has many libraries and frameworks that can help you build powerful applications.

from https://www.revechat.com/wp-content/themes/revechat/images/chatbot/cb-hero-top.png

You can download and install Python from the official website. Make sure you select the latest version of Python 3.x for your operating system (Windows, Mac OS, or Linux). You can also use an integrated development environment (IDE) such as PyCharm. or Visual Studio Code to write and run your Python code.

After installing Python, you will need to install some essential libraries and frameworks to build a chatbot. This includes:

  • ChatterBot: A library that allows you to build a simple chatbot with minimal coding
  • spaCy: A library that provides natural language processing (NLP) capabilities for text analysis and comprehension.
  • Sasa: A framework that allows you to create conversational agents with intent and action.

You can install these libraries and frameworks using pip, which is a package manager for Python. To install pip, open a command prompt or terminal and type:

python -m ensurepip — upgrade

This will install or upgrade pip on your PC. Then, to install ChatterBot, spaCy, and Sasa type:

pip install chatterbot
pip install spacy
pip install rasa

This will download and install the latest version of these libraries and frameworks on your PC. You may also need to download some additional data or models for these libraries and frameworks to work properly. For example, to use spaCy for English processing, you would download the English model by typing:

python -m spacy download en_core_web_sm

This will download and install the small English model for spaCy. You can also download other models for different languages ​​or sizes from the spaCy website.

Step 2: Create a simple chatbot using ChatterBot

Now that you have installed Python and the necessary libraries and frameworks on your PC, you can start building your local chatbot. The first step is to create a simple chatbot using ChatterBot.

ChatterBot is a library that allows you to build a simple chatbot with minimal coding. ChatterBot uses logic adapters to generate responses based on user input. A logic adapter is a module that selects a response from a list of possible responses based on some criteria or logic.

ChatterBot comes with several built-in logic adapters that can handle common conversation types, such as greetings, compliments, timing, or math. You can also create your own custom logic adapters or use multiple logic adapters together to create more complex chatbots.

To create a simple chatbot using ChatterBot, you need to import the ChatBot class from the chatterbot module and create an instance of it. You can also specify the name of the chatbot and the logical adapter that you want to use in the constructor of the ChatBot class.

For example, the following code creates a simple chatbot named Bob that uses two logical adapters: one to handle greetings and another to handle time-related questions.

from chatterbot import ChatBot
# Create a chatbot named Bob
bob = ChatBot(
“Bob”,
logic_adapters=[
“chatterbot.logic.BestMatch”,
“chatterbot.logic.TimeLogicAdapter”
]
)

The BestMatch logic adapter selects the best response from a list of possible responses based on the similarity between the inputs and responses. The TimeLogicAdapter logic adapter returns the current time when the input contains a time-related query.

To interact with your chatbot, you need to create a loop that takes input from the user and passes it to the get_response() method of the ChatBot class. This method returns a response object that contains the response text. You can print the response text using the str() function.

For example, the following code creates a loop that lets you chat with Bob until you type “Bye” or “Exit”.

# Chat with Bob
while True:
# Get the input from the user
user_input = input(“You: “)
# Check if the user wants to exit
if user_input.lower() in [“bye”, “exit”]:
print(“Bob: Goodbye!”)
break
# Get the response from Bob
response = bob.get_response(user_input)
# Print the response
print(“Bob:”, str(response))

The output of this code might look something like this:

You: Hi
Bob: Hello
You: What is your name?
Bob: My name is Bob.
You: What time is it?
Bob: The current time is 11:15 AM.
You: Bye
Bob: Goodbye!

As you can see, Bob can respond to simple greetings and questions about the time. However, Bob might not be able to handle other types of questions or conversations. For example, if you ask Bob about his favorite hobby or movie, he may not have the right answer.

To make your chatbot smarter and more versatile, you need to enhance it with natural language processing using spaCy.

Step 3: Improve your chatbot with natural language processing using spaCy

Natural language processing (NLP) is a branch of artificial intelligence that deals with analyzing and understanding human language. NLP can help you build chatbots that can process and interpret natural language input from users and produce natural language output for users.

spaCy is a library that provides NLP capabilities for text analysis and comprehension. spaCy can perform various NLP tasks, such as tokenization, lemmatization, part-of-speech tagging, named entity recognition, dependency parsing, and text classification.

To enhance your chatbot with NLP using spaCy, you need to import the spacy module and load the model for the language you want to use. For example, if you want to use English, you need to load the en_core_web_sm model that you downloaded earlier.

import spacy
# Load the English model
nlp = spacy.load(“en_core_web_sm”)

The nlp object is a language pipeline that can process text and return a Doc object that contains various information and attributes about the text. For example, you can access tokens, lemmas, part-of-speech, entities, dependencies, and text sentences using nlp objects.

To use spaCy with your chatbot, you need to process user input and chatbot output using nlp objects. This will allow you to analyze and understand both sides of the conversation and come up with a more appropriate response.

For example, you can use spaCy to extract named entities from user input and use them in your chatbot output. Named entities are words or phrases that refer to specific real-world objects or concepts, such as people, places, organizations, dates, or events.

To extract named entities from text using spaCy, you need to use the ents attribute of the Doc object. This attribute returns a tuple of Span objects that represent the named entity in the text. Each Span object has various attributes, such as text, label_, and start_char.

For example, the following code extracts a named entity from user input and prints it with its label and position.

# Get the input from the user
user_input = input(“You: “)
# Process the input using spaCy
doc = nlp(user_input)
# Extract named entities from the input
entities = doc.ents
# Print each entity along with its label and position
for entity in entities:
print(entity.text, entity.label_, entity.start_char)

The output of this code might look something like this:

You: I live in New York and work for Google.
New York GPE 10
Google ORG 29

As you can see, spaCy has identified two named entities in user input: New York (geopolitical entity) and Google (organization). You can use these entities in your chatbot output to make it more personalized and relevant.

any named entity in user input and use it in chatbot output. For example, the following code creates a custom logic adapter that responds to user input “I live in New York and work for Google” with “Wow, you live in a great city and work for a great company”.

from chatterbot.logic import LogicAdapter
# Create a custom logic adapter
class EntityLogicAdapter(LogicAdapter):
# Initialize the logic adapter
def __init__(self, chatbot, **kwargs):
super().__init__(chatbot, **kwargs)
# Load the spaCy model
self.nlp = spacy.load(“en_core_web_sm”)
# Generate a response based on the input
def generate_response(self, input_statement, additional_response_selection_parameters):
# Process the input using spaCy
doc = self.nlp(input_statement.text)
# Extract named entities from the input
entities = doc.ents
# Check if there are any entities
if entities:
# Create a list of entity texts
entity_texts = [entity.text for entity in entities]
# Join the entity texts with commas and “and”
entity_string = “, “.join(entity_texts[:-1]) + “ and “ + entity_texts[-1]
# Create a response text using the entity string
response_text = “Wow, you live in a great city and work for a great company”
# Create a response object with the response text
response = Statement(text=response_text)
# Set the confidence of the response to 1.0
confidence = 1.0
else:
# Create an empty response object
response = Statement(text=””)
# Set the confidence of the response to 0.0
confidence = 0.0
# Return the response and the confidence
return confidence, response

In order to use this particular logical adapter with your chatbot, you need to add it to the list of logical adapters in the constructor of the ChatBot class. For example, the following code adds EntityLogicAdapter to Bob.

# Create a chatbot named Bob
bob = ChatBot(
“Bob”,
logic_adapters=[
“chatterbot.logic.BestMatch”,
“chatterbot.logic.TimeLogicAdapter”,
EntityLogicAdapter
]
)

Now, if you chat with Bob using the same loop as before, you might get something like this:

You: Hi
Bob: Hello
You: What is your name?
Bob: My name is Bob.
You: What time is it?
Bob: The current time is 11:30 AM.
You: I live in New York and work for Google.
Bob: Wow, you live in a great city and work for a great company.

As you can see, Bob can now use the named entity from your input in his output. This makes Bob more responsive and personal.

However, Bob may still not be able to handle complex or specific questions or requests. For example, if you ask Bob to book a flight for you or order pizza for you, he may not give the right answer.

To make your chatbot more powerful and versatile, you need to create a conversational agent with intent and action using Sasa.

Step 4: Build a conversational agent with intent and action using Sasa

Conversational agents are chatbots that can understand the intent and context of user input and take appropriate action based on that input. Conversation agents can handle different types of conversations, such as ordering, ordering, scheduling, or recommending.

Sasa is a framework that allows you to create conversational agents with intent and action. Sasa consists of two main components: Sasa NLU and Sasa Core.

  • NLU Sasa is the component that takes care of natural language understanding (NLU). It can extract intents and entities from user input using machine learning models.
  • Sasa Core is the component that takes care of dialog management (DM). It can predict the next action to be taken based on user input, conversation history, and predefined policies.

To build a conversation agent using Sasa, you need to follow these steps:

  • Define your domain: Your domain is a file that contains information about your conversation agent, such as intent, entity, action, slot, response, and form. You can write your domain in YAML format and save it as domain.yml.
  • Write your story: Your story is a file containing examples of how your conversational agent should behave in different situations. You can write your story in Markdown format and save it as stories.md.
  • Train your model: You can train your model using the train Sasa command. This will train the Sasa NLU and Sasa Core models using your domain and story files.
  • Test your model: You can test your model using shell Sasa commands. This will allow you to chat with your conversation agent in the terminal and see how it responds to your input.

For example, say you want to create a conversation agent that can book hotels for you. You can define your domain as follows:

# domain.yml
# Define the intents
intents:
- greet
- book_hotel
- affirm
- deny
- goodbye
# Define the entities
entities:
- location
- checkin
- checkout
- budget
# Define the slots
slots:
location:
type: text
checkin:
type: text
checkout:
type: text
budget:
type: text
# Define the actions
actions:
- utter_greet
- utter_ask_location
- utter_ask_checkin
- utter_ask_checkout
- utter_ask_budget
- utter_confirm_booking
- utter_thank_you
- utter_goodbye
# Define the responses
responses:
utter_greet:
— text: “Hello, welcome to HotelBot. How can I help you?”
utter_ask_location:
— text: “Where do you want to stay?”
utter_ask_checkin:
— text: “When do you want to check in?”
utter_ask_checkout:
— text: “When do you want to check out?”
utter_ask_budget:
— text: “What is your budget per night?”
utter_confirm_booking:
— text: “Okay, I have booked a hotel for you in {location} from {checkin} to {checkout} for {budget} per night. Is that correct?”
utter_thank_you:
— text: “You’re welcome. Have a nice day.”
utter_goodbye:
— text: “Goodbye. See you soon.”

You can write your story as follows:

# stories.md
# Story 1: Successful booking
* greet
— utter_greet
* book_hotel{“location”: “Paris”, “checkin”: “2023–05–10”, “checkout”: “2023–05–15”, “budget”: “$100”}
— slot{“location”: “Paris”}
— slot{“checkin”: “2023–05–10”}
— slot{“checkout”: “2023–05–15”}
— slot{“budget”: “$100”}
— utter_confirm_booking
* affirm
— utter_thank_you
* goodbye
— utter_goodbye
# Story 2: Unsuccessful booking
* greet
— utter_greet
* book_hotel{“location”: “London”, “checkin”: “2023–06–01”, “checkout”: “2023–06–07”, “budget”: “$200”}
— slot{“location”: “London”}
— slot{“checkin”: “2023–06–01”}
— slot{“checkout”: “2023–06–07”}
— slot{“budget”: “$200”}
— utter_confirm_booking
* deny
— action_restart

You can train your model by typing:

rasa train

This will create a models folder containing your trained models. You can test your model by typing:

rasa shell

This will allow you to chat with your conversation agent on the terminal. The output might look something like this:

Your input -> Hi 
Hello, welcome to HotelBot. How can I help you?
Your input -> I want to book a hotel
Where do you want to stay?
Your input -> Paris
When do you want to check in?
Your input -> May 10th
When do you want to check out?
Your input -> May 15th
What is your budget per night?
Your input -> $100
Okay, I have booked a hotel for you in Paris from May 10th to May 15th for $100 per night. Is that correct?
Your input -> Yes
You’re welcome. Have a nice day.
Your input -> Bye
Goodbye. See you soon.

As you can see, your conversation agent can handle simple ordering scenarios. However, your conversation agent may not be able to handle more complex or diverse scenarios. For example, if you want to change or cancel your booking, or if you want to request a recommendation or review, your conversation agent may not have the appropriate response.

To make your conversation agent more powerful and flexible, you need to test and improve it.

Step 5: Test and improve your chatbot

Testing and improving your chatbot is an ongoing process that involves evaluating and improving the performance and functionality of your chatbot. Testing and improving your chatbot can help you identify and fix any errors or problems with your chatbot, such as:

  • Spelling
  • Grammar or syntax errors
  • Logical or factual errors
  • Relevance or coherence error
  • Diversity or creativity of errors

There are various methods and tools that can help you test and improve your chatbot, such as:

  • Unit testing: Unit testing is a method that allows you to test individual components or functionality of your chatbot, such as logic adapters, actions or models. You can use unit tests to check if your chatbot behaves as expected in various scenarios and feedback. You can use a framework like pytest or unittest to write and run unit tests for your chatbot.
  • Evaluation: Evaluation is a method that allows you to measure the quality and performance of your chatbot using metrics such as accuracy, precision, recall or F1 score. You can use evaluations to compare different versions or configurations of your chatbot and identify the best one. You can use tools like Taste Test or Sense X to evaluate your chatbot using your stories and data.
  • Debugging: Debugging is a method that allows you to identify and fix any errors or problems in your chatbot using tools such as logs, breakpoints or interactive shells. You can use debugging to check and change the status and behavior of your chatbot at any time during a conversation. You can use tools like Rasa shell or Rasa interactive to debug your chatbot in the terminal.
  • Feedback: Feedback is a method that allows you to collect and analyze the opinions and suggestions of your users or testers about your chatbot. You can use the feedback to improve the usability, functionality and personality of your chatbot. You can use tools like Flavor forms or Flavor surveys to gather feedback from users or testers using your chatbot.

By regularly testing and improving your chatbot, you can ensure that it meets your expectations and requirements, and provides a satisfying and enjoyable experience for your users.

By following these steps, you can create a local chatbot that works offline and with 100% privacy. You can also customize and expand your chatbot according to your needs and preferences.

I hope you enjoyed this article and learned something new. If you have any questions or feedback, please leave a comment below. Happy coding!

reference

--

--

Andika Wirawan

I am Andika Wirawan, welcome. I work as a freelancer and enjoy reading and writing. I appreciate you reading my writing.