Tracker和Event
在Rasa Core中Tracker負(fù)責(zé)記錄整個對話的流程较沪,而Tracker中數(shù)據(jù)的新增鳞绕、編輯和刪除是通過Event進(jìn)行管理的。
Policy
Policy是負(fù)責(zé)決策Action的調(diào)用在Tracker的狀態(tài)發(fā)生變更之后尸曼,Policy來決定下一步的Action们何。
Action
Action是對用戶輸入的一種回應(yīng):
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并提供對應(yīng)方法即可骡苞。普通的Action是通過run方法來實現(xiàn)功能垂蜗,例如講一個笑話:
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會進(jìn)行表單校驗,要求用戶提供指定的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來調(diào)用這些Action提供服務(wù)烘苹。
Agent
Agent將Rasa Core的功能通過API開放出來,像模型訓(xùn)練片部,對話處理等都可以通過Agent完成镣衡,一個模型訓(xùn)練的例子:
import sys
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.agent import Agent
if len(sys.argv) < 3:
print("請指定數(shù)據(jù)路徑和模型的存儲名稱")
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服務(wù)的入口,通過Agent來訪問Rasa Core提供的功能档悠。