Reader small image

You're reading from  Conversational AI with Rasa

Product typeBook
Published inOct 2021
PublisherPackt
ISBN-139781801077057
Edition1st Edition
Tools
Right arrow
Authors (2):
Xiaoquan Kong
Xiaoquan Kong
author image
Xiaoquan Kong

Xiaoquan is a machine learning expert specializing in NLP applications. He has extensive experience in leading teams to build NLP platforms in several Fortune Global 500 companies. He is a Google developer expert in Machine Learning and has been actively involved in contributions to TensorFlow for many years. He also has actively contributed to the development of the Rasa framework since the early stage and became a Rasa Superhero in 2018. He manages the Rasa Chinese community and has also participated in the Chinese localization of TensorFlow documents as a technical reviewer.
Read more about Xiaoquan Kong

Guan Wang
Guan Wang
author image
Guan Wang

Guan is currently working on Al applications and research for the insurance industry. Prior to that, he was a machine learning researcher at several industry Al labs. He was raised and educated in Mainland China, lived in Hong Kong for 10 years before relocating to Singapore in 2020. Guan holds BSc degrees in Physics and Computer Science from Peking University, and an MPhil degree in Physics from HKUST. Guan is an active tech blogger and community contributor to open source projects including Rasa, receiving more than10,000 stars for his own projects on Github.
Read more about Guan Wang

View More author details
Right arrow

Chapter 3: Rasa Core

In this chapter, we introduce how to implement dialogue management in Rasa. Rasa Core is the component in Rasa that handles dialogue management. Dialogue management is responsible for keeping a record of the conversation context and choosing the next actions accordingly.

The dialogue management system can be divided into four parts. Dialogue state tracking updates the dialogue state according to the previous round of dialogue and the previous round of system actions, as well as the user's intentions and entities in the current round. The dialogue policy is responsible for outputting dialogue actions according to the dialogue state. The dialogue action is based on the decision of the dialogue strategy to interact with the backend interface to complete the actual task execution. And finally, the dialogue result output outputs the result of the system operation in a user-friendly way.

In Rasa Core, these functions have all been integrated, and users can...

Technical requirements

In this chapter, we will introduce a new Python package called rasa-sdk. It has exactly the same dependencies as rasa. We already introduced this in Chapter 1, Introduction to Chatbots and the Rasa Framework. Specifically, you need a Python 3.6, 3.7, or 3.8 environment to successfully install the software.

You can find all the files for this chapter in the ch03 directory of the GitHub repository at the following URL: https://github.com/PacktPublishing/Conversational-AI-with-RASA.

Understanding the universe of your bot (domain)

A domain defines all the information a chatbot needs to know, including intents, entities, slots, actions, forms, and responses. All this information gives clear definitions of the inputs and outputs of a model.

A sample domain file is as follows:

intents:
  - greet
  - goodbye
  - affirm
  - thank_you
entities:
  - name
slots:
  name:
    type: text
responses:
  utter_greet:
    - "hey there {name}!" # {name} is template variable
  utter_goodbye:
    - "goodbye"
    - "bye bye"
  utter_default:
    - "default message"
actions:
  - utter_default
  - utter_greet
  - ...

Training data for dialogue management (stories)

Rasa learns from conversations and manages knowledge by training on stories. The story is a high-level semantic way of recording conversations. It records not only the expressions from users, but also the correct state change within the system.

Rasa uses YAML format to store stories. Here is an example of a story:

stories:
  - story: This is the description of one story
    steps:
      - intent: greet
      - action: action_ask_howcanhelp
      - slot_was_set:
          - asked_for_help: true
      - intent: inform
        entities:
          - location: "New York"
          - price:...

Reacting to user input (action)

The action receives user input and the conversation state and processes these according to business logic. It outputs events that change the conversation state and messages to reply to the user. There are four types of actions: response actions, form actions, built-in actions, and custom actions. Let's start with the simplest: response actions.

Response actions

This type of action is linked to the responses in the domain. When this type of action is called, the system will automatically search for the same name templates within the responses and render them. Since response actions need to have the same name with their responses, they need to start with utter_.

In the next section, we will talk about form actions.

Form actions

One important mode for task-oriented conversation is to continuously interact with users and collect elements that are needed by the tasks until the required information is complete. This mode is usually referred...

Understanding the memory of your bot (slots)

The slot is the memory of the chatbot. The slot is represented as a key-value pair, such as city: New York. It records the key information from conversations. The key information can come from a user's input (intents and entities), or from backend systems (for example, the result from a payment action: success or failure). Normally, the information is crucial for the flow of the conversation and will be used by the dialogue management system to predict the next action.

Let's take an example. In a simple application of a weather forecast, the information of location and date is key for the dialogue management system to decide the next action. If the system finds either the location or date missing, it will ask users for the corresponding information until both are present. Then the system will start to query some weather APIs.

Here, the system only cares about whether the location and date slots are filled. It does not care...

Understanding the decision-maker of your bot (policies)

The policy method learns from stories and predicts the next actions.

Policies need to use a featurizer to convert stories into conversational states, get the state features, and use those features to predict the next action.

In Rasa, we can have multiple policies. Policies are trained independently and can be used together for final prediction according to their priorities and confidence scores.

Let's start with policy configuration.

Configuring policies

Policy configuration is done in the config.yaml file within a Rasa project. The part with key policies is reserved for policy configuration. Here is an example:

policies:
  - name: "MemoizationPolicy"
    max_history: 5
  - name: "FallbackPolicy"
    nlu_threshold: 0.4
    core_threshold: 0.3
    fallback_action_name: "my_fallback_action...

Connecting with other services via endpoints

As a mature dialogue system, Rasa supports communication with external services and internal components in a similar way to microservices. In Rasa's terminology, all links to these services are called endpoints. The endpoint is the connection between Rasa Core and other services and is defined in endpoints.yml. Currently, the supported endpoints are as follows:

  • Event broker: This allows you to connect your bot to other services that can process conversation data asynchronously. The event broker publishes messages to a message broker in order to forward conversations from Rasa to external services. This is useful for advanced users who want to analyze the conversations.
  • Tracker store: Rasa's conversations are stored within a tracker store. Rasa provides several built-in tracker stores. In general, all tracker stores can be divided into two categories: the tracker store that is exclusive to the process and the tracker...

Building custom actions using Rasa SDK

Custom actions provide a mechanism to run specific actions in remote servers. This is crucial for building a chatbot, as it is the gateway for implementing detailed business logic.

Installing the Rasa SDK package

Rasa integrates rasa-sdk in its package. So, when you install Rasa, it will also automatically install rasa-sdk. If we want to use rasa-sdk alone (for example, in a production environment), we can run the following command:

pip install rasa-sdk

Writing custom actions

Custom actions must inherit the Action class from the SDK, so that the server can automatically discover and register the custom actions. Here is an example:

from rasa_sdk import Action
from rasa_sdk.events import SlotSet
class ActionCheckRestaurants(Action):
   def name(self) -> Text:
      return "action_check_restaurants"
   def run(self,
         ...

Using channels to communicate with instant messaging software

In most cases, users will be using all kinds of instant messaging (IM) apps to interact with chatbots.

Rasa is one of the best platforms for seamlessly integrating with different IMs. Rasa supports most of the mainstream IMs on the market that support OpenAPI. Currently, it includes Facebook Messenger, Slack, Telegram, Twilio, Microsoft Bot Framework, Cisco Webex Teams, RocketChat, Mattermost, and Google Hangouts Chat.

Community developers have also developed many open source IMs for Rasa, and those open source IMs are often used by start-ups and developers for product demonstration purposes. Rasa Webchat (https://github.com/botfront/rasa-webchat) and Chatroom (https://github.com/scalableminds/chatroom) have the most mature functionalities.

In Rasa, the connector is responsible for connecting a Rasa system to an IM. The Connect feature handles the communication protocol. Since different IMs may share the same communication...

Building a tell-the-time bot

A tell-the-time bot is one of the most basic and simplest chatbots. It is very suitable as an introductory exercise project, allowing learners to understand what each part of the Rasa system does. All the project files can be found under the directory named ch03 in the GitHub repository, available at the following URL: https://github.com/PacktPublishing/Conversational-AI-with-RASA. Let's start by outlining the target functions this bot should provide.

Defining the features that our bot should provide

In this section, we will list all the functions this exercise project should provide. Let's start with greetings and goodbyes.

Handling greetings and goodbyes

Example #1: The bot responds to the user's greeting, as follows:

User: Hello!
Bot: Hello, my name is Silly. I can help you get the time and date. You may ask me "What time is it?", "What's the date today?" or "What day is it tomorrow?".
...

Summary

In this chapter, we discussed Rasa Core. This is the dialogue management part of Rasa. You should now have a good understanding of how to define all the key concepts for Rasa Core: domain, response, story, action, slot, and policy. You should also have a good understanding of how to use Rasa SDK to develop your own custom actions, and how to connect Rasa Core with IM software and use Rasa to develop simple chatbots.

In the next chapter, we will take a deeper look at how to handle business logic effectively in Rasa.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Conversational AI with Rasa
Published in: Oct 2021Publisher: PacktISBN-13: 9781801077057
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Xiaoquan Kong

Xiaoquan is a machine learning expert specializing in NLP applications. He has extensive experience in leading teams to build NLP platforms in several Fortune Global 500 companies. He is a Google developer expert in Machine Learning and has been actively involved in contributions to TensorFlow for many years. He also has actively contributed to the development of the Rasa framework since the early stage and became a Rasa Superhero in 2018. He manages the Rasa Chinese community and has also participated in the Chinese localization of TensorFlow documents as a technical reviewer.
Read more about Xiaoquan Kong

author image
Guan Wang

Guan is currently working on Al applications and research for the insurance industry. Prior to that, he was a machine learning researcher at several industry Al labs. He was raised and educated in Mainland China, lived in Hong Kong for 10 years before relocating to Singapore in 2020. Guan holds BSc degrees in Physics and Computer Science from Peking University, and an MPhil degree in Physics from HKUST. Guan is an active tech blogger and community contributor to open source projects including Rasa, receiving more than10,000 stars for his own projects on Github.
Read more about Guan Wang