对话机器人 Rasa(二十二):返回自定义补充字段

发布时间: 2023-08-31 20:28:08 作者: 大象笔记

需求

前端访问 Rasa 接口获取聊天对话的应答信息,除了想获取 text,和 buttons 之外,还想获取额外的信息。 例如,多个操作按钮对应的 item id。

查了很久才找到一点线索,然后尝试了一圈,发现两个可行的方法。

方案一: custom action

直接在 custom action python 代码中,utter_message 中指定 custom 字典参数:

custom_data = {
	"field1": "value1",
	"field2": "value2",
	"item_id": "www.sunzhongwei.com"
}
dispatcher.utter_message(
	text="Hello World!",
	custom=custom_data
)

或者使用 domain 中的模板

dispatcher.utter_message(
	response="utter_hello_world",
	custom={
		"item_id": "www.sunzhongwei.com"
	},
)

返回的数据格式:

[
    {
        "recipient_id":"user_id",
        "text":"Hello world",
        "buttons":[
            {
                "title":"文章不错",
                "payload":"\/good"
            },
            {
                "title":"文章起飞",
                "payload":"\/great"
            }
        ]
    },
    {
        "recipient_id":"user_id",
        "custom":{
            "item_id":"www.sunzhongwei.com"
        }
    }
]

注意,这里是分两条消息返回的,第二条是对应的附加字段;第一条则是正常的 text / buttons 格式。

只需要判断 key 是否是 custom 即可。

方案二: domain yaml

utter 中添加一个 custom 字段,里面是具体的附加信息:

utter_hello_world:
- text: "Hello world!"
  buttons:
  - title: "文章可以"
    payload: '/good'
  - title: "文章一般可以"
    payload: '/great'
  custom:
    item_id: "{item_id}"

然后定义一个 slot,方便 custom action 在之前流程中设置。

返回格式同上。

错误的做法

utter_hello_world:
- text: "Hello www.sunzhongwei.com"
  item_id: "123"
  buttons:
  - title: "Button A"
    payload: '/A'
  - title: "Button B"
    payload: '/B'

执行 rasa train 训练对话模型时,会收到报错信息:

YamlValidationException: Failed to validate '/some_path/domain.yml'. Please make sure the file is correct and all mandatory parameters are specified. Here are the errors found during validation:
  in /some_path/domain.yml:432:
      Key 'item_id' was not defined. Path: '/responses/utter_hello_world/0'
make: *** [Makefile:7: train] Error 1

更复杂的情况

可以把所有字段都放到 custom 中:

  utter_complex_response:
  - custom:
      format: "markdown"
      text: "#title \ncontent"

json

domain 中添加 custom 字段,是可以返回 json 结构的。

即添加更多内嵌的字段:

utter_hello:
- custom:
    site:
      name: "大象笔记"
      link: "www.sunzhongwei.com"

查看合集

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

参考

我是一名山东烟台的开发者,联系作者