Tracker和Event
在Rasa Core中Tracker负责记录整个对话的流程,而Tracker中数据的新增、编辑和删除是通过Event进行管理的。
Policy
Policy是负责决策Action的调用在Tracker的状态发生变更之后,Policy来决定下一步的Action。
Action
Action是对用户输入的一种回应:
Actions are the things your bot runs in response to user input. There are three kinds of actions in Rasa Core:
- default actions (
action_listen
,action_restart
,action_default_fallback
)- utter actions, starting with
utter_
, which just sends a message to the user.- custom actions - any other action, these actions can run arbitrary code
Action的自定义比较简单,只需要继承Action并提供对应方法即可。普通的Action是通过run方法来实现功能,例如讲一个笑话:
from rasa_core_sdk import Action
class ActionJoke(Action):
def name(self):
# define the name of the action which can then be included in training stories
return "action_joke"
def run(self, dispatcher, tracker, domain):
# what your action should do
request = requests.get('http://api.icndb.com/jokes/random').json() #make an apie call
joke = request['value']['joke'] #extract a joke from returned json response
dispatcher.utter_message(joke) #send the message back to the user
return []
另一种常用的Action是FromAction,这种Action会进行表单校验,要求用户提供指定的slots:
class UserInfoForm(FormAction):
"""Example of a custom form action"""
def name(self):
# type: () -> Text
"""Unique identifier of the form"""
return "userinfo_form"
@staticmethod
def required_slots(tracker):
# type: () -> List[Text]
"""A list of required slots that the form has to fill"""
return ["user_name"]
def submit(self, dispatcher, tracker, domain):
# type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
"""Define what the form has to do
after all required slots are filled"""
# utter submit template
# dispatcher.utter_template('utter_info_basic', tracker)
response = {
"intent": "user_info_basic",
"slots":[
tracker.get_slot("user_name")
]
}
dispatcher.utter_message(json.dumps(response))
# dispatcher.utter_attachment(*elements)
return []
在Action定义完成后需要在domain中添加,并且需要ActionServer来调用这些Action提供服务。
Agent
Agent将Rasa Core的功能通过API开放出来,像模型训练,对话处理等都可以通过Agent完成,一个模型训练的例子:
import sys
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.agent import Agent
if len(sys.argv) < 3:
print("请指定数据路径和模型的存储名称")
exit()
domain = "{}/domain.yml".format(sys.argv[1])
stories = "{}/data/stories.md".format(sys.argv[1])
dialogue = "{}/models/{}".format(sys.argv[1], sys.argv[2])
agent = Agent(domain, policies=[KerasPolicy(validation_split=0.0,epochs=400)])
training_data = agent.load_data(stories)
agent.train(training_data)
agent.persist(dialogue)
Agent可以作为Rasa Core服务的入口,通过Agent来访问Rasa Core提供的功能。
网友评论