对话机器人 Rasa(十一):custom actions 中使用 python 设置 slot 值

更新日期: 2023-07-01 阅读次数: 1472 字数: 1045 分类: AI

例如,我想在 Rasa 对话过程中,缓存当前用户选择的服务 ID。 方便在调用其他业务接口时使用该 slot 的值。

custom actions 代码示例

actions.py 中,假设要将 my_slot 设置为 some_value:

from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.events import SlotSet

class MyCustomAction(Action):
    def name(self) -> Text:
        return "my_custom_action"

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

        # Set the value of the 'my_slot' slot to 'some_value'
        return [SlotSet("my_slot", "some_value")]

为何 action run 函数要 return

可以看到上面示例代码中,SlotSet 是在 return 中设置的,那么这个 return 有什么意义呢?

return 返回值的作用是告诉 Rasa Core 下一步应该采取什么行动。

run 函数返回的是一个包含一系列事件的列表,这些事件描述了 Rasa Core 应该如何响应用户的输入。通常情况下,这个列表中包含一个消息事件,用来向用户发送一个文本消息。例如:

return [SlotSet("name", name), FollowupAction("utter_greet")]

这里,run 函数返回了一个包含两个事件的列表。

  • 第一个事件是 SlotSet 事件,用来将一个名为 name 的 slot 设置为 name 变量的值。
  • 第二个事件是 FollowupAction 事件,用来指示 Rasa Core 接下来应该执行一个名为 utter_greet 的 action,向用户发送一个问候消息。

另一个示例, 来自:

https://learning.rasa.com/archive/conversational-ai-2/custom-actions/

很好的说明了,什么时候该 return 事件列表,什么时候 return 空列表。 即,在未获取到有用信息的时候,return 空列表。

class ActionRememberWhere(Action):

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

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        current_place = next(tracker.get_latest_entity_values("place"), None)
        utc = arrow.utcnow()

        if not current_place:
            msg = "I didn't get where you lived. Are you sure it's spelled correctly?"
            dispatcher.utter_message(text=msg)
            return []

        tz_string = city_db.get(current_place, None)
        if not tz_string:
            msg = f"I didn't recognize {current_place}. Is it spelled correctly?"
            dispatcher.utter_message(text=msg)
            return []

        msg = f"Sure thing! I'll remember that you live in {current_place}."
        dispatcher.utter_message(text=msg)

        return [SlotSet("location", current_place)]

还学到了一招:

current_place = next(tracker.get_latest_entity_values("place"), None)

The custom action tries to fetch a detected entity for a place. If it cannot find one in the tracker, it tries to fail gracefully. This is a pattern that you'll see a lot in custom actions. You should always consider how to best catch unexpected behavior.

很奇怪,这么好的文档为啥没有出现在 Rasa 3 里。

custom action 中获取 slot

timezone_in = tracker.get_slot("location")

domain.yml 中的 slot 定义

主要要将 slot type 设置成 custom (应该是代表 custom action), 而不是 from_text (会导致默认将聊天会话中的最后一条信息作为 slot 值,从而出现奇怪的值,哈哈,悲剧地调试了一上午)

slots:
  location:
    type: text
    influence_conversation: true
    mappings:
    - type: custom

如果不设置 mappings,会报错:(Rasa 3.4.6)

Cannot find required key 'mappings'. Path: '/slots/location'

参考:

https://rasa.com/blog/how-to-use-global-slot-mappings/

Rasa 官方 blog 中给出的示例是:

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

实际测试,不加这个 action 也没有发现问题,一切正常运行。

事件是什么

from rasa_sdk.events import SlotSet

这里提到了 run 函数 return 的是一个事件的列表,而且 SlotSet 也是定义在 rasa_sdk.events 中。

那么,到底 Rasa 事件是什么呢?

在 Rasa 中,事件用于描述对话流程中的各种动作和状态变化,例如发送消息、设置 slot 值、执行 custom action 等等。事件是 Rasa Core 在对话管理中非常重要的组成部分,它们可以帮助 Rasa Core 确定下一步应该采取什么行动。

Rasa 中常见的事件包括:

  1. UserUttered:表示用户发出了一条消息。
  2. BotUttered:表示机器人发出了一条消息。
  3. SlotSet:表示设置了一个 slot 的值。
  4. ActionExecuted:表示执行了一个 action。
  5. Restarted:表示对话被重启了。
  6. AllSlotsReset:表示所有 slot 被重置了。
  7. ConversationPaused:表示对话被暂停了。
  8. FollowupAction:表示执行了一个跟随 action。
  9. ReminderScheduled:表示设置了一个提醒。
  10. ReminderCancelled:表示取消了一个提醒。

在 Rasa Core 中,每个事件都包含了事件类型、事件参数等信息。当一个事件被触发时,Rasa Core 会根据事件类型和参数来执行相应的操作,例如发送消息、设置 slot 值等。事件是 Rasa Core 实现对话管理的核心机制之一,它可以帮助 Rasa Core 实现复杂的对话流程控制和状态管理。

查看合集

📖 对话机器人 Rasa 中文系列教程

tags: rasa

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式