How to send Custom Json Response from Rasa Chatbot's Custom Action? - GeeksforGeeks

16 Mar, 2021
Rasa is an open-source Machine Learning framework to automate contextual text-voice-based Assistant. Rasa NLU understands the correct Intent with the help of its pre-trained nlu data. Rasa Core decides what to do next and reply according to in sync with the training stories. It also has the capability to store Entities (Noun type-specific Information stored for future use).  By default, it can respond with texts, image links, button objects etc.
To get started with your own contextual assistant, just simply install Rasa with the help of below mentioned command:
pip install rasa
Make sure you have the latest version of  PIP installed this will install the latest version of rasa 2.0,  if you face any difficulty with the version of python then please install Python 3.6.8 creating a virtual environment.
Creating a rasa project is very simple, rasa gives you an inbuilt command to create a sample project for you. 
rasa init 
After executing this command successfully you will get a directory structure containing a list of files, you can check the created files by typing “ls -la” on your terminal. Working upon it, we will be able to train our rasa model to perform various tasks according to our requirements.
The nlu.yml file inside the “data” folder contains the various training data to extract Intents and Entities.
The stories.yml file inside the “data” folder contains the sample user stories for training the chatbot which rasa core will make use of it and predicts the next suitable action/response.
The config.yml file contains configuration relating to the Machine Learning pipeline using which a sentence will be preprocessed and used by the nlu and core model.
The domain.yml file contains list of Intents, Entities, Responses and Actions, each of these things should be listed in the domain file. 
The actions.py file inside the actions folder contains various python functions for each custom action defined in the domain.yml file. This is a very useful file as it contains the action definitions which will be performed by the bot on specific intents, be it performing some calculations on the data, calling API’s and many more which a python function can perform.
The format of writing these files will automatically be provided by the sample project we create with the help of “rasa init”. We just have to add our own training data, list the intents, responses and write the required custom action and we are good to go.
We can train our model with the help of a simple command written below:
rasa train
After the model is trained we can test our model in the terminal itself through a simple command provided below:
rasa shell 
With this, we can start the conversation with the bot and tests our trained model. We can also use the –debug flag to see the various parameters such as the confidence, intents detected, next response, entities captured, etc, these will help us know the insights of the model and can further train the model in a better way to get more accurate responses.
Rasa provides its user with a lot of capabilities, it can perform any task just by writing a python class with some methods to fulfill the requirements. These functions are written in the actions.py file. Each function is attached with a specific action name starting with the “action_” keyword which should be mentioned accurately in the domain.yml file as well as in the user stories written in the stories.yml file. This custom action is triggered after a specific intent is captured by the nlu, it will perform the coded tasks and then will return the required responses.
Below is the sample custom action code to get a better understanding:
We can start the action server by opening a new terminal window, navigate to the project directory and run the below-provided command:
rasa run actions
Let’s see the below command which will help us to retrieve the stored entities present inside the local bot memory:
variable_name = tracker.latest_message['entities']
The “tracker” keeps the record of the recent conversations and the stored entity. The above command will return an array of stored entities. We will have to Iterate through this array to get our desired entity value. 
Normally a bot sends a text message (string) as a response (Refer to the above-given screenshot) but the challenge comes when we have to send some custom response in the form of JSON data to satisfy the needs of the end-users of the bot.
Let’s define a Use case where we will have to use a Custom response and send the JSON data back to the UI channel.
Assume the Rasa-bot stored some user data in between the conversation and now the User wants a list of his/her provided details. Here comes the task of sending Custom Response in the form of JSON data which will help the front-end developer to segregate the response and easily populate the data in the UI.
Below is the Python code to write the Custom Action method, which will retrieve the user stored entities and return the appropriate values:
Python3
class ListUserDetails(Action):      def name(self) -> Text:        # Name of the action mentioned in the domain.yml file        return "action_list_user_details"      def run(self, dispatcher: CollectingDispatcher,            tracker: Tracker,            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:          # It will return array of entities        entities = tracker.latest_message['entities']          # Iterating through the array to retrieve the desired entity        for e in entities:            if e['entity'] == "user_name":                entity_name = e['value']            elif e['entity'] == "city_name":                entity_city = e['value']            elif e['entity'] == "designation":                entity_designation = e['value']          dispatcher.utter_message(            template="utter_user_details",            name=entity_name,            city=entity_city,            designation=entity_designation        )          return []
Written above is a sample custom action Python code of the Rasa chat-bot to perform a particular desired action on understanding the exact intent from the user. Here Rasa NLU takes the user’s message and finds out the correct intent which in the above case is “Listing all the user details”. 
After this Rasa calls the custom action (action_list_user_details) associated with the particular intent and performs the task. In the above code we are fetching the user details stored as an entity inside the local memory of the bot such as name, city, and designation with the help of the tracker and sending the fetched result as a single response to the template “utter_user_details” with the help of dispatcher.utter_message( )
The above code will call the “utter_user_details” response mentioned in the domain.yml file with the fetched user details as arguments. Lastly, we have to write the response “utter_user_details” in the domain.yml file using the custom keyword to send a JSON object to the channel as a response to the user’s message. Below is the format of the response:
Following this method, a JSON response with the provided attribute will be sent to the respective output channel. The output of the below code will look similar to this:
Similarly using the Custom response we can send the required data in the JSON format which can be handled well by the front-end developer.
Technical Scripter 2020
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Intuition of Adam Optimizer
Singular Value Decomposition (SVD)
ML | Logistic Regression using Python
Adding new column to existing DataFrame in Pandas
Read JSON file using Python
Python map() function
How to get column names in Pandas dataframe