Building a chatbot with Python and Rasa

As technology advances, chatbots are becoming an increasingly popular way for businesses to engage with their customers. A chatbot is a computer program that can simulate conversations with humans using natural language. By building a chatbot, businesses can provide their customers with quick and easy access to information, while freeing up their customer service staff to focus on more complex issues.
In this guide, we will explore how to build a chatbot using Python and Rasa, an open-source framework for building conversational AI. Whether you’re new to chatbot development or an experienced programmer, by the end of this article, you’ll have the knowledge to start building your own chatbot.
Introduction to Chatbots and Rasa
Chatbots have become an integral part of our daily digital interactions. They assist us in customer support, booking appointments, ordering products and more. Building a chatbot can be a complex task, but with Rasa, an open-source machine-learning framework, the process is much smoother.
Rasa consists of two main components, Rasa NLU (Natural Language Understanding) and Rasa Core. Rasa NLU handles the understanding of user messages, while Rasa Core manages the dialogue flow and responses. Together, these components allow us to create sophisticated chatbots with ease.
In this guide, we’ll use Python and Rasa to build a chatbot capable of handling user queries and providing useful responses. Through this process, you’ll gain a deeper understanding of how chatbots work and the role Rasa plays in their development.
2. Setting up the Environment
Before we begin, we need to set up our development environment. First, make sure you have Python 3.6 or higher installed. You can check your Python version with the following command:
python --version
Next, we’ll create a virtual environment to isolate our project dependencies. Run the following commands:
python -m venv my_chatbot_env
source my_chatbot_env/bin/activate # On Windows, use `my_chatbot_env\Scripts\activate`
Now that your virtual environment is activated, let’s install Rasa:
pip install rasa
This command will install Rasa and all the necessary dependencies. Once the installation is complete, you’re ready to start building your chatbot!
3. Creating a New Rasa Project
To create a new Rasa project, run the following command:
rasa init --no-prompt
This command creates a new Rasa project with the default configuration and example files. The resulting project structure should look like this:
├── actions
│ └── actions.py
├── config.yml
├── credentials.yml
├── data
│ ├── nlu.yml
│ └── stories.yml
├── domain.yml
├── endpoints.yml
└── models
In the next sections, we’ll modify these files to define our chatbot’s behavior and train it to understand user messages.
4. Defining Intents and Entities
Intents represent the purpose of a user’s message, while entities are specific pieces of information extracted from the message. To define intents and entities, edit the data/nlu.yml
file.
First, let’s add some example user messages for each intent:
nlu:
- intent: greet
examples: |
- Hi
- Hello
- Hey
- intent: ask_weather
examples: |
- What's the weather like today?
- How is the weather?
- Tell me the weather
- intent: goodbye
examples: |
- Bye
- Goodbye
- See you later
Now, let’s add an entity for the location in the ask_weather
intent:
- intent: ask_weather
examples: |
- What's the weather like in [New York](location)?
- How is the weather in [London](location)?
- Tell me the weather for [Tokyo](location)
By annotating the location in square brackets and specifying the entity type in parentheses, Rasa will learn to extract the location from user messages.
Configuring the NLU Pipeline
The NLU pipeline is a series of components responsible for processing user messages and extracting useful information. To configure the pipeline, edit the config.yml file.
Here’s an example configuration:
language: en
pipeline:
name: WhitespaceTokenizer
name: RegexFeaturizer
name: LexicalSyntacticFeaturizer
name: CountVectorsFeaturizer
name: CountVectorsFeaturizer
analyzer: "char_wb"
min_ngram: 1
max_ngram: 4
name: DIETClassifier
epochs: 100
name: EntitySynonymMapper
name: ResponseSelector
epochs: 100
name: FallbackClassifier
threshold: 0.3
ambiguity_threshold: 0.1
This pipeline includes various components for tokenization, featurization and classification, as well as a fallback classifier for handling unrecognized messages.
Building Custom Actions
Custom actions allow your chatbot to perform more advanced tasks, such as querying an API or performing calculations. To create custom actions, edit the actions/actions.py
file.
For example, let’s create a custom action to fetch the weather data for a given location:
from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
import requests
class ActionGetWeather(Action):
def name(self) -> Text:
return "action_get_weather"
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
location = tracker.get_slot("location")
weather_data = self.get_weather_data(location)
dispatcher.utter_message(text=weather_data)
def get_weather_data(self, location: Text) -> Text:
api_key = "your_api_key"
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}"
response = requests.get(url)
data = response.json()
return f"The weather in {location} is {data['weather'][0]['description']}."
Remember to replace "your_api_key"
it with a valid OpenWeatherMap API key. You can obtain one for free from their website.
Configuring the Dialogue Management
Dialogue management in Rasa is responsible for determining the flow of the conversation. To configure the dialogue management, edit the data/stories.yml
file.
Here’s an example story for our weather chatbot:
stories:
- story: ask_weather
steps:
- intent: greet
- action: utter_greet
- intent: ask_weather
- action: action_get_weather
- intent: goodbye
- action: utter_goodbye
This story defines a simple conversation flow where the user greets the chatbot, asks for the weather and then says goodbye.
Training and Testing the Chatbot
To train your chatbot, run the following command:
rasa train
This command will train both the NLU and dialogue management models. Once the training is complete, you can test your chatbot using the Rasa shell:
rasa shell
Now, you can interact with your chatbot and see how it responds to various user messages.
Deploying the Chatbot
To deploy your chatbot, you can use Rasa X, a platform for managing and deploying Rasa-powered chatbots. First, install Rasa X:
pip install rasa-x --extra-index-url https://pypi.rasa.com/simple
Next, run the following command to launch Rasa X:
rasa x
Conclusion
In conclusion, Rasa X provides a web-based interface for managing your chatbot, including version control, conversation tracking and integration with various messaging platforms. That’s it! You’ve successfully built and deployed a chatbot using Python and Rasa. As you’ve seen, Rasa simplifies the process of building and deploying chatbots, enabling you to create sophisticated and powerful conversational agents.