当我们需要从前端传递额外参数到rasa后端时,需要我们自定义连接器来实现。
https://rasa.com/docs/rasa/connectors/custom-connectors
import asyncio
import inspect
from sanic import Sanic, Blueprint, response
from sanic.request import Request
from sanic.response import HTTPResponse
from typing import Text, Dict, Any, Optional, Callable, Awaitable, NoReturn
import rasa.utils.endpoints
from rasa.core.channels import (
InputChannel,
CollectingOutputChannel,
UserMessage,
)
class MyIO(InputChannel):
def name(cls) -> Text:
return "myio"
def __init__(self) -> None:
self.custom_metadata = {
}
def blueprint(
self, on_new_message: Callable[[UserMessage], Awaitable[Any]]
) -> Blueprint:
custom_webhok = Blueprint(
"custom_webhook_{}".format(type(self).__name__),
inspect.getmodule(self).__name__,
)
@custom_webhok.route("/", methods=["GET"])
async def health(request: Request) -> HTTPResponse:
return response.json({
"status": "ok"})
@custom_webhok.route("/webhook", methods=["POST"])
async def receive(request: Request) -> HTTPResponse:
sender_id = request.json.get("sender")
text = request.json.get("text")
input_channel = self.name()
metadata = self.get_metadata(request)
collector = CollectingOutputChannel()
await on_new_message(
UserMessage(
text,
collector,
sender_id,
input_channel=input_channel,
metadata=metadata,
)
)
# 响应
return response.json(collector.messages)
return custom_webhok
def get_metadata(self, request: Request) -> Optional[Dict[Text, Any]]:
return request.json.get("metadata", None)
添加一行:
addons.custom_channel.MyIO:
addons是rasa项目下的文件夹名,custom_channel是连接器脚本文件名,MyIO是连接器类名
只有在action_seesion_start可以获取元数据,rasa默认的action_seesion_start是忽略元数据的,所以需要重写该Action。
根据槽值名称session_started_metadata来获取前端传递过来的元数据
class ActionSessionStart(Action):
def name(self) -> Text:
return "action_session_start"
async def run(
self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]
) -> List[Dict[Text, Any]]:
# 获取字典类型的元数据
metadata = tracker.get_slot("session_started_metadata")
print(metadata)
return [SessionStarted(),ActionExecuted("action_listen")]```
由于我们重写了rasa的默认Action,所以需要在domain文件中申明
添加:
actions:
- action_session_start
由于我们重写了rasa的默认Action,所以需要添加参数**–force**强制训练使其生效。
cmd命令行:
rasa train --force
前置条件:
请求地址为(myio为连接器名,与连接器脚本中相对应):
http://127.0.0.1:5005/webhooks/myio/webhook
请求参数为:
{
"sender": "user",
"text": "你好",
"metadata":{
"location":"116.08243,22.44579","address":"福建省厦门市"}
}
metadata为字典类型,可以在metadata中添加你想要传递给后端的参数