How to Create a Chatbot with Rasa and Python

With the increasing popularity of chatbots, more and more businesses are turning to the technology to automate customer support and provide personalized experiences. Rasa is an open-source machine learning framework that allows developers to build, improve, and deploy their own AI-powered chatbots. In this tutorial, we will walk through the process of creating a chatbot with Rasa and Python.

Table of Contents

Note: This tutorial assumes that you have basic knowledge of Python and the command line.

Introduction to Rasa

Rasa is an open-source framework for building AI-powered chatbots. It provides two main components: Rasa NLU for natural language understanding and Rasa Core for handling dialogue flows. With these tools, you can design conversational AI agents that can understand user inputs and generate appropriate responses.

Rasa NLU allows you to define intents, which represent the goal or meaning behind a user’s message, and entities, which are specific pieces of user information. On the other hand, Rasa Core handles the sequential aspect of conversation, allowing you to define a dialogue flow through a set of stories and design custom actions to perform specific tasks in response to user inputs.

Setting up the Development Environment

To get started with Rasa, you’ll need to set up your development environment. Follow these steps to install the required dependencies:

  1. Install Python: Rasa requires Python 3.6 or higher. If you don’t have Python installed, you can download it from the official Python website and follow the installation instructions.
  2. Create a Virtual Environment: It’s always a good practice to work within a virtual environment to prevent conflicts with other Python projects. Open a command prompt or terminal and run the following command to create and activate a virtual environment:

    python3 -m venv myenv
    source myenv/bin/activate     # For Mac/Linux
    .myenvScriptsactivate      # For Windows
    
  3. Install Rasa: With your virtual environment activated, run the following command to install Rasa:
    pip install rasa
    
  4. Verify Installation: After the installation is complete, make sure Rasa is set up correctly by running the following command to display the version:
    rasa --version
    

    You should see the version number of Rasa, indicating a successful installation.

Now that your development environment is ready, let’s move on to designing conversations using stories.

Designing Conversations using Stories

Stories are a key component of Rasa Core. They represent sample conversations between a user and a chatbot and define the flow of the conversation. Each story consists of a series of user inputs (intents) and the corresponding bot responses.

To design a conversation, create a new file called stories.md. Here’s an example of a simple story:

## greeting
* greet
  - utter_greet

## goodbye
* goodbye
  - utter_goodbye

In this example, the story starts with the intent greet. When the user sends a message with the intent greet, the bot responds with the template utter_greet. Similarly, when the intent goodbye is detected, the bot responds with utter_goodbye.

With Rasa, you can define complex dialogues by using slots, which allow the bot to store and retrieve information during the conversation. Here’s an example of a story with slots:

## order_pizza
* greet
  - utter_greet
* order_pizza
  - slot{"pizza_type": "unknown"}
  - utter_ask_pizza_type
* inform{"pizza_type": "margherita"}
  - slot{"pizza_type": "margherita"}
  - utter_ask_pizza_size
* inform{"pizza_size": "large"}
  - slot{"pizza_size": "large"}
  - utter_confirm_order
* affirm
  - action_submit_order
  - utter_order_confirmation
* goodbye
  - utter_goodbye

In this example, the bot starts by greeting the user. Then, it prompts the user to order a pizza by asking for the pizza type. The answer to this question is stored in the pizza_type slot. The bot then asks for the size of the pizza and stores it in the pizza_size slot. Finally, it confirms the order and takes action to submit the order information.

By designing conversations with stories, you can define dialogue flows that have multiple paths based on user inputs. Now let’s move on to defining intents and entities.

Defining Intents and Entities

Intents represent the goal or meaning behind a user’s message, while entities are specific pieces of user information. To define intents and entities in Rasa, you can create two separate files called nlu.md and domain.yml.

The nlu.md file contains examples of user inputs, along with the associated intents and entities. Here’s an example:

## intent:greet
- hey
- hello
- hi
- good morning

## intent:goodbye
- bye
- goodbye
- see you later

## intent:order_pizza
- i want to order a pizza
- can i get a pizza?
- let's order pizza

In this example, we have defined three intents: greet, goodbye, and order_pizza. Each intent consists of several examples of user inputs that represent the same meaning.

The domain.yml file defines the entities, slots, and responses for the chatbot. Here’s an example:

intents:
  - greet
  - goodbye
  - order_pizza

entities:
  - pizza_type
  - pizza_size

slots:
  pizza_type:
    type: unfeaturized
  pizza_size:
    type: unfeaturized

responses:
  utter_greet:
    - text: "Hello! Welcome to our pizza bot."
  utter_goodbye:
    - text: "Goodbye! Have a great day."
  utter_ask_pizza_type:
    - text: "What type of pizza would you like to order?"
  utter_ask_pizza_size:
    - text: "What size would you like (small, medium, or large)?"
  utter_confirm_order:
    - text: "You ordered a {pizza_size} {pizza_type} pizza. Is that correct?"
  utter_order_confirmation:
    - text: "Your order has been received. Enjoy your pizza!"

In this example, we define two entities, pizza_type and pizza_size. We also define two slots for storing the values of these entities. The responses are predefined templates that the bot uses to generate responses during the conversation.

Note that this is a simple example and you can define more complex intents, entities, and responses as needed for your chatbot. Now let’s move on to creating NLU training data.

Creating NLU Training Data

NLU training data is used to train a machine learning model to understand user inputs. In Rasa, the training data is defined in the nlu.md file that we created earlier.

To create the training data, we can use Rasa’s rasa shell nlu command. This command allows you to interactively test and annotate your training data.

  1. Open a command prompt or terminal and navigate to the project directory where you have the nlu.md file.
  2. Run the following command to start the interactive training session:

    rasa shell nlu
    

    This will launch the interactive shell where you can enter example user inputs and annotate them with the correct intents and entities.

  3. Enter an example user input and press Enter. For example, you can enter “Hello, I want to order a pizza.”

  4. The shell will display the detected intents and entities, along with the confidence scores. If the detected intents and entities are correct, you can press Enter to continue. Otherwise, you can manually correct them.

  5. Continue entering example user inputs until you have a sufficient amount of training data.

  6. After you finish annotating the training data, press Ctrl + C to exit the interactive shell.

The annotated training data will be automatically saved in the nlu.md file. You can now move on to building the dialogue model.

Building the Dialogue Model

The dialogue model is responsible for managing the flow of the conversation and generating appropriate responses based on user inputs. In Rasa, the dialogue model is defined using stories and custom actions.

To build the dialogue model, create a new file called domain.yml. This file contains the definitions for intents, entities, slots, and responses, as well as the stories.

To train the dialogue model, use Rasa’s rasa train command. This command reads the stories and training data, and trains a machine learning model to understand user inputs and generate responses.

Here’s the command to train the model:

rasa train

After the training is complete, the trained model will be saved in the models directory.

Handling Custom Actions

Custom actions allow you to define custom behavior in response to user inputs. Actions can perform a wide range of tasks, such as calling external APIs, querying databases, or executing business logic.

To define a custom action, create a new Python file and subclass rasa_sdk.Action. Here’s an example:

from rasa_sdk import Action
from rasa_sdk.events import SlotSet

class SubmitOrderAction(Action):
    def name(self):
        return "action_submit_order"

    def run(self, dispatcher, tracker, domain):
        pizza_type = tracker.get_slot("pizza_type")
        pizza_size = tracker.get_slot("pizza_size")

        # Code to submit the order and get the confirmation number
        confirmation_number = "123456"

        dispatcher.utter_message("Your order has been received. Confirmation number: {}".format(confirmation_number))

        return [SlotSet("pizza_type", None), SlotSet("pizza_size", None)]

In this example, we define a custom action called SubmitOrderAction. The name method returns the name of the action, which will be used when defining the action in the stories.

The run method is called when the action is triggered. It receives three parameters: dispatcher, tracker, and domain. The dispatcher is used to send messages to the user, while the tracker gives you access to the conversation history and slot values. The domain provides access to the domain definitions.

Inside the run method, you can perform any task needed to handle the action. In this example, we retrieve the values of the pizza_type and pizza_size slots and use them to submit the order. We then send a message to the user with the confirmation number and reset the slots to their initial values.

Now that we have defined the custom action, we can update the domain.yml file to include it in the response templates.

Training the Chatbot

After defining the stories, NLU training data, and the dialogue model, it’s time to train the chatbot.

To train the chatbot, run the following command:

rasa train

This command will read the stories, NLU training data, and the dialogue model file, and train a machine learning model using the Rasa framework.

Training the chatbot might take some time, depending on the complexity of your training data and the size of your model. After the training is complete, the trained model will be saved in the models directory.

Testing the Chatbot

To test the chatbot, use Rasa’s rasa test command. This command reads a test data file with sample conversations and evaluates the bot’s performance.

To test the chatbot, follow these steps:

  1. Create a test data file called test.md. Here’s an example:
    ## order_pizza
    * greet
     - utter_greet
    * order_pizza
     - slot{"pizza_type": "unknown"}
     - utter_ask_pizza_type
    * inform{"pizza_type": "margherita"}
     - slot{"pizza_type": "margherita"}
     - utter_ask_pizza_size
    * inform{"pizza_size": "large"}
     - slot{"pizza_size": "large"}
     - utter_confirm_order
    * affirm
     - action_submit_order
     - utter_order_confirmation
    * goodbye
     - utter_goodbye
    

    This file contains the sample conversations that you want to test.

  2. Run the following command to test the chatbot:

    rasa test
    

    This command will evaluate the bot’s performance by comparing the predicted actions and responses with the expected ones from the test data.

After running the test, Rasa will display the evaluation results, including the accuracy, precision, and F1-score.

Deploying the Chatbot

Once you are satisfied with the performance of your chatbot, it’s time to deploy it to a production environment.

Rasa provides several deployment options, including running the chatbot as a web server, integrating it into a messaging platform like Facebook Messenger or Slack, or deploying it as a REST API.

You can find detailed instructions on how to deploy your chatbot in the Rasa Documentation.

Conclusion

In this tutorial, we have learned how to create a chatbot with Rasa and Python. We started by setting up the development environment and defining conversations using stories. Then, we defined intents and entities, created NLU training data, and built the dialogue model. We also learned how to handle custom actions, train and test the chatbot, and deploy it to a production environment.

Rasa provides a powerful set of tools and libraries to create intelligent chatbots that can understand user inputs, generate contextual responses, and perform complex tasks. With Rasa, you have full control over the behavior of your chatbot and can easily customize it to fit your specific needs.

I hope this tutorial has given you a good understanding of how to create a chatbot with Rasa and Python. Now it’s time to unleash your creativity and build your own AI-powered chatbot!

Related Post