对话机器人 Rasa(十七):python custom actions 将 list 或 dict 存储到 slot

文章目录

    需求场景

    在 rasa custom actions 的 python 代码中,需要调用一些三方 http api,并对查询结果进行缓存。

    例如,调用天气查询接口一次查询未来三天的天气。将三天的结果放到一个 slot 中缓存。然后,用户通过聊天对话询问某一天的天气时,就可以直接返回 cache 中的结果,无需每次都调用三方接口。

    rasa slot 是否支持 list,dict 类型

    之前只用过 slot 存储 text,number 这样简单的基础数据类型。不确定是否支持 list 和 dict 这样的类型。

    查了一下 rasa 的官方文档,确实支持,只需要将 slot 类型设置成 any。

    Any type:

    Storing arbitrary values (they can be of any type, such as dictionaries or lists).

    domain.yml

    domain 中定义 slot

    slots:
      items:
        type: any
        influence_conversation: false
        mappings:
        - type: custom
    

    注意:influence_conversation 需要设置为 false。因为只有在 story 中使用了 slot 影响对话逻辑的情况才应该设置为 true。实际上,这里用于缓存的 slot,并没有出现在 story 中,所以也就没有必要设置为​ true 了。

    Slots of type any are always ignored during conversations. The property influence_conversation cannot be set to true for this slot type. If you want to store a custom data structure which should influence the conversation, use a custom slot type.

    custom action

    # set slot
    items = [1, 2, 3]
    SlotSet("items", items)
    
    # get slot
    items = tracker.get_slot("items")
    

    查看合集

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

    参考

    https://rasa.com/docs/rasa/domain/#any-slot

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式