Rasa course, Rasa training, Rasa interview, Rasa's new global word slot mapping in Rasa combat series 3 major methods

Rasa course, Rasa training, Rasa interview, Rasa's new global word slot mapping in Rasa combat series 3 major methods

In Rasa 3.0, Rasa has enabled "Global Slot Mapping" for better control over conversational information in chatbots.

Slots store information during a conversation, such as username, account number, and whether to book a flight or train. Slot mapping is the process of collecting and preparing this information so that the dialogue policy can use it to choose the next action or insert it into the bot's response template. In Rasa 3.0, we have enabled "Global Slot Mapping", which gives better control over the information.

In this blog post, we'll show you three new ways to use global slot mapping in the Rasa assistant to solve common problems and unlock new features.

Decide what your bot should do based on external information

Suppose we want the robot to behave differently depending on the time of day. For example, if the user asks to chat with a human, and the time is outside office hours, the bot should tell the office hours and keep trying to solve the user's problem. But if it's during office hours, the bot should hand off the conversation to a human operator.

This is an example of a high-level decision, so we want to use feature word slots that influence the policy. Therefore, we define an office_open word slot, use the slot to be True when the office is open, and False otherwise.

slots:
  office_open:
    type: bool
    influence_conversation: true
    mappings:
    - type: custom
      action: action_set_office_open

The value of slot is set in action_set_office_open, we need to define it in action server

class ActionSetOfficeOpen(Action):


    def name(self) -> Text:
        return "action_set_office_open"


    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]
    ) -> List[Dict[Text, Any]]:
        office_open = random.choice([True, False]) # just for debugging
        return [
            SlotSet("office_open", office_open)
        ]

This code will now run after every user message, keeping office_open up to date, the name "action" may be confusing, this is not an action predicted by the policy, it's just a piece of code that runs at the end of the NLU pipeline.

With the office_open word slot, we can now define the robot's behavior in two short rules***:

- rule: Deal with request_human at office hours
  steps:
  - intent: request_human
  - slot_was_set:
    - office_open: true
  - action: utter_handover_to_human  # Just an example for the demo


- rule: Deal with request_human outside office hours
  steps:
  - intent: request_human
  - slot_was_set:
    - office_open: false
  - action: utter_office_hours

This was not possible until we introduced global slot mapping in Rasa. You either have to train the policy to do a custom action that populates the office_open location, or you have to handle the decision in a custom action that either passes the working hours to the human, or prints the office hours.

Rules are written in the same way as stories, but they usually only represent snippets of dialogue. Whenever the bot encounters a dialog that matches a rule, RulePolicy executes the next action defined by the rule.

Use a dummy word slot to fill multiple word slots at the same time

The usual YAML format for a slot map indicates that all slots are filled independently, and there is a mapping for each slot (custom slot filling operation). However, for most applications, where slot values ​​are interdependent, it is better to declare a function that performs all the mappings.

To do this, you define a dummy slot with a custom mapping

slots:
  dummy:
    type: any
    influence_conversation: false
    mappings:
    - type: custom
      action: global_slot_mapping

And fill all the slots from the global_slot_mapping function using a custom action written for this purpose.
Example: Setting a policy conditional on a low score for an extracted entity
With the office_open word slot, we let the robot react to external information (time of day). But since the slot mapping action has access to the dialogue history (tracker object), we can also set the slot based on the properties of the dialogue, including information that does not normally enter the policy, such as entity extraction confidence scores.

Suppose we add a form to our bot where the bot asks for the item type and the last known location when the user lost the item. Slots and forms are now defined in the field as

slots:
  dummy:
    type: any
    mappings:
    - type: custom
      action: global_slot_mapping
  # Featurized slots for policies
  office_open:
    type: bool
    influence_conversation: true
    mappings:
    - type: custom
  low_entity_score:
    type: bool
    influence_conversation: true
    initial_value: false
    mappings:
    - type: custom
  # Unfeaturized slots for forms
  lost_item_type:
    type: text
    influence_conversation: false
    mappings:
    - type: custom
  last_known_item_location:
    type: text
    influence_conversation: false
    mappings:
    - type: custom
  # Unfeaturized slots for NLG
  unclear_entity_value:
    type: text
    influence_conversation: false
    mappings:
    - type: custom


forms:
  main_form:
    required_slots:
      - lost_item_type
      - last_known_item_location

You will see that only the dummy word slot has a word slot map operation. This action is now responsible for the entire mapping process:

class GlobalSlotMapping(Action):


    def name(self) -> Text:
        return "global_slot_mapping"


    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]
    ) -> List[Dict[Text, Any]]:
        new_slot_values: Dict[Text, Any] = dict()


        # Office hours
        new_slot_values["office_open"] = random.choice([True, False])


        # Entity mapping and low entity score handling
        low_entity_score: bool = False
        for entity_type, value, score in get_entity_data(tracker.latest_message):
            print(f"{
      
      entity_type}: {
      
      value} ({
      
      score})")
            if score < 0.98:
                low_entity_score = True
                new_slot_values["unclear_entity_value"] = value
            else:
                if entity_type == "item":
                    new_slot_values["lost_item_type"] = value
                elif entity_type == "location":
                    new_slot_values["last_known_item_location"] = value
        new_slot_values["low_entity_score"] = low_entity_score


        return [
            SlotSet(name, value)
            for name, value in new_slot_values.items()
        ]

Now we can define a rule to handle low extraction scores:

- rule: Handle low entity score in main form
  condition:
  - active_loop: main_form
  steps:
  - intent: inform
  - slot_was_set:
    - low_entity_score: true
  - action: utter_entity_unclear
  - action: main_form
  - active_loop: main_form

Our bot can have the following conversations:

Your input ->  hi                                                                                                                                                                                      
Hello! How can I help you?
I am Lost & Found Bot and can help you find things.
Your input ->  i lost my umbrella                                                                                                                                                                      
Where did you last see your item?
Your input ->  on the tran                                                                                                                                                                             
I'm not sure what you mean by 'tran'.
Where did you last see your item?
Your input ->  i mean, on the train                                                                                                                                                                    
You are looking for 'umbrella', last seen at 'train'

Note that the confidence scores of entity extractors are not necessarily reliable. It can easily happen that entities are extracted incorrectly and still have very high scores. Retraining your model may also drastically change the confidence score.

Generate responses using word slots

We have just seen how to define a global word slot map to influence policy decisions through feature word slots. Alternatively, we can skip the strategy in the information flow graph and only affect response generation through uncharacterized word slots.

Given a response template ( utter_* ), word slots can affect the bot's response in two ways: for response conditions or as variables.

Example: Handling Duplicate Questions

If users ask the same question over and over again, you may want your bot to give a more detailed answer. For example, if the user keeps asking about the capabilities of the bot, and the bot replies with utter_abilities, you don't want the bot to always say the exact same thing. But you also don't want to randomly choose between responsive templates. Using a global slot map, you can do this by keeping track of how often the bot utter_abilities executes, putting this information into the slot num_utter_abilities, and defining this response template to condition on that slot.

The utter_abilities response could be:

responses:
  utter_abilities:
  - text: "I am Lost & Found Bot and can help you find things."
    condition:
      - type: slot
        name: num_utter_abilities
        value: 0
  - text: "I can help you find things that you've lost either on a train or some other place in town."
    condition:
      - type: slot
        name: num_utter_abilities
        value: 1
  - text: "Actually, I'm just a demo, so don't expect me to really find something."
    condition:
      - type: slot
        name: num_utter_abilities
        value: 2
  - text: "I can't do anything beyond what I already mentioned, sorry."

num_utter_abilities keep the word slots up to date using the following code in the word slot mapping function:

class GlobalSlotMapping(Action):


    def name(self) -> Text:
        return "global_slot_mapping"


    def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]
    ) -> List[Dict[Text, Any]]:
        new_slot_values: Dict[Text, Any] = dict()


        # ...


        # Count how often the bot executed `utter_abilities`
        num_utter_abilities = 0
        for event in tracker.applied_events():
            if event_is_action(event, "utter_abilities"):
                num_utter_abilities += 1
        new_slot_values["num_utter_abilities"] = num_utter_abilities


        return [
            SlotSet(name, value)
            for name, value in new_slot_values.items()
        ]

We have to define some new intents and appropriate rules for your bot to respond correctly:

- rule: Respond to ask_what_can_do
  steps:
  - intent: ask_what_can_do
  - action: utter_abilities
  - intent: tell_me_more     # for this to work, set `restrict_rules: false` for the RulePolicy
  - action: utter_abilities
  - intent: tell_me_more
  - action: utter_abilities

Our bot can have the following conversations:

Your input ->  hi                                                                                      
Hello! How can I help you?
I am Lost & Found Bot and can help you find things.
Your input ->  what can you do?                                                                        
I can help you find things that you've lost either on a train or some other place in town.
Your input ->  what else?                                                                              
Actually, I'm just a demo, so don't expect me to really find something.
Your input ->  tell me more                                                                            
I can't do anything beyond what I already mentioned, sorry.

This is a very simple application. But in principle, you can use slot mapping to adjust your response template based on whatever information you can extract from the conversation history (or external sources). For example, you could add a lightweight classifier to your NLU pipeline and tailor your responses to the user's writing style. But remember to only set your bot's responses to things you know for sure about your users.

in conclusion

As you can see, global slot mapping introduces many new features to Rasa Open Source that might not be immediately apparent when you first learn about them. They are a flexible and powerful new feature, and we look forward to seeing how they can solve all kinds of problems for you.

Rasa Course Resources Released

Introduction to Gavin

The founder of Xingkong Intelligent Dialogue Robot and the author of the AI ​​universal two-line thinking method, he is currently working in the top AI laboratory in Silicon Valley. Specializing in Conversational AI. Worked in Silicon Valley's top machine learning and artificial intelligence labs in the United States

Gavin big coffee WeChat: NLP_Matrix_Space

Tel: +1 650-603-1290

Contact Email: [email protected]

Teaching assistant teacher WeChat: Spark_AI_NLP
insert image description here
insert image description here

Rasa 3.x series blog sharing

Guess you like

Origin blog.csdn.net/duan_zhihua/article/details/124349826