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


Introduction

Rasa Chatbot's developer-friendly custom actions allow for the generation of arbitrary JSON answers. It facilitates the development of dynamic and customized JSON answers. Rasa Chatbot is a flexible platform for developing conversational AI chatbots. Natural language processing and conversational management are brought together in this paradigm. Using custom actions, programmers can instruct the chatbot to perform very precise tasks. Calls to APIs and database queries fall within this category. Developers can improve the chatbot's usability by making use of dynamic material and formatting that is specific to each user by means of custom JSON answers.

Setting up Rasa Chatbot to Send out Custom JSON Responses

To have your Rasa Chatbot's custom actions deliver personalized JSON responses, you'll need to perform a few extra steps.

First, let's define what we mean by "custom actions," which are snippets of Python code that direct your robot's behavior. Creating a custom action to generate the desired JSON structure allows for the sending of personalized JSON responses. This is an example of a custom action that returns data in JSON format.

Python source −

from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

class CustomAction(Action):
   def name(self) -> Text:
      return "action_send_json_response"

   def run(self, dispatcher: CollectingDispatcher,
      tracker: Tracker,
      domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
      # Generate the custom JSON response
      json_response = {
         "message": "This is a custom JSON response",
         "data": {
            "key": "value"
         }
      }
      # Send the custom JSON response
      dispatcher.utter_message(json_message=json_response)
      return []

Secondly,  Custom Response Configuration in Domain File The chatbot can be programmed to use predefined custom response templates that can be defined in the Rasa domain file. Defining a template with a JSON structure allows you to configure a unique JSON response. So, to illustrate −

Yaml code

responses:
   utter_custom_json_response:
   - text: '{"message": "This is a custom JSON response", "data": {"key": "value"}}'

Creating Custom JSON Response Templates

Creating response templates in your domain file is another option for configuring unique JSON responses. The conversational context can be incorporated into these templates in a dynamic way. So, to illustrate −

Yaml code

responses:
   utter_custom_dynamic_json_response:
   - text: '{"message": "This is a custom JSON response", "data": {"entity_value": "{entity_name}"}}'

Third, Creating Custom JSON Responses in Rasa Chatbot's Custom Action

Accessing User Input and Context in Custom Actions

To create one-of-a-kind JSON responses for Rasa Chatbot, you can access user input and the current context within your custom action code. User input, chat history, and other configuration options are all accessible through the 'tracker' object. 'tracker.latest_message['text']' will return the most recent user message, whereas 'tracker.events' will return historical events.

Generating Custom JSON Responses Programmatically

You can create dynamic JSON responses with the code for your own action. The structure of the JSON response and the contents to fill it can be determined based on the user's input and the required logic. Creating data in JSON format is as easy as populating a dictionary object with key-value pairs. The modified JSON answer can then be sent back to the user through the dispatcher object. The following is a code snippet −

Python code

from typing import Any, Dict, List, Text
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
class CustomAction(Action):
   def name(self) -> Text:
      return "custom_action"

   def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
      # Generate custom JSON response dynamically
      custom_response = {
         "key1": "value1",
         "key2": "value2",
         # Add more key-value pairs as needed
      }

      # Send the custom JSON response
      dispatcher.utter_message(json_message=custom_response)
      return []

Formatting Custom JSON Responses

The structure and content of the returned JSON data can be modified to meet your needs. Whether it's text, graphics, buttons, or something else, you're free to include it. The response must be structured in a way that is compatible with the JSON syntax specifications. The chatbot's intended functionality relies on a well-formed JSON answer.

Next, Sending Custom JSON Response from Rasa Chatbot's Custom Action

Scenario Overview

In this example, we'll show you how to use the custom action in Rasa Chatbot to send a personalized JSON response. Let's pretend the chatbot's job is to respond in depth to a user's question about a certain product by consulting a database.

Defining Custom Action in Python

To get started, a Python custom action will be defined to manage the data retrieval mechanism. Here's a sample chunk of code −

Python code

from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

class RetrieveProductInfoAction(Action):
   def name(self) -> Text:
      return "action_retrieve_product_info"

   def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
      # Logic to retrieve product information based on user input
      product_info = self.get_product_info(tracker.latest_message["text"]) 
      # Custom JSON response
      response = {
         "type": "product_info",
         "data": product_info
      } 
      dispatcher.utter_message(json_message=response)
      return []

Creating Custom JSON Response Template

To proceed, a unique JSON response template outlining the response's structure must be developed. You can modify this sample to fit your needs by adding or removing sections. So, to illustrate −

Json code

{
   "type": "product_info",
   "data": {
      "product_name": "",
      "description": "",
      "price": 0.0,
      "availability": ""
   }
}

Sending Custom JSON Response From Custom Action

In the custom action's 'run()' method, we retrieve the necessary data and save it in the 'product_info' variable. The 'product_info' is then used in conjunction with the established template to generate the individualized JSON response. To complete the process, we return the parsed JSON to the user through the 'dispatcher.utter_message()' method.

You may get your Rasa Chatbot to deliver customized JSON responses by following these instructions and tailoring them to your needs.

Testing and Troubleshooting Custom JSON Responses in Rasa Chatbot

To ensure the quality and functionality of bespoke JSON answers in Rasa Chatbot, rigorous testing and troubleshooting is required. The following steps must be taken −

  • Performing local tests to ensure proper execution of custom actions.

  • Investigating typical problems, including wrong formatting or incomplete data retrieval, that occur with bespoke JSON answers.

  • Checking that generated and delivered custom JSON replies within the Rasa Chatbot framework are correct.

Developers can assure the robustness and efficiency of their Rasa Chatbot implementation by adhering to these techniques for testing and troubleshooting bespoke JSON answers.

Best Practices for Custom JSON Responses in Rasa Chatbot's Custom Action

To improve the readability and maintainability of your replies, it's important to arrange them in JSON with explicit keys and values.

Adapting to a Wide Range of Situations with Personalized JSON Replies − Modify JSON replies based on user intents or actions for more nuanced and relevant conversations.

Custom JSON Responses' Error Handling and Fallbacks − The chatbot's ability to gracefully manage unforeseen events and provide helpful information to users depends on the sophisticated error handling mechanisms and fallback strategies implemented inside the JSON answers.

Conclusion

The conclusion of this section offers a succinct summary of the major points covered in relation to the custom action of Rasa Chatbot's JSON responses. At first, we'll review how custom JSON answers work and why they're useful. The article then describes why and how bespoke JSON answers are useful in chatbot creation. In the end, it stresses how crucial it is to improve chatbot interactions by making better use of specific JSON answers. This robust capability allows developers to tailor Rasa Chatbot interactions to each individual user.

Someswar Pal
Someswar Pal

Studying Mtech/ AI- ML

Updated on: 29-Sep-2023

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements