該文是Rasa官網文檔的一個簡單翻譯,用於平常查看。html
官網文檔地址:Rasa文檔python
推薦經過pip
命令安裝Rasagit
pip install rasa-x --extra-index-url https://pypi.rasa.com/simple
複製代碼
該命令會安裝Rasa
和Rasa X
。若是不想使用Rasa X
,使用pip install rasa
替換便可。 除非你已經安裝了numpy和scipy,不然咱們強烈建議你安裝和使用Anaconda
。github
若是您想使用Rasa的開發版本,能夠從GitHub獲取:web
git clone https://github.com/RasaHQ/rasa.git
cd rasa
pip install -r requirements.txt
pip install -e .
複製代碼
Windows先決條件算法
確保安裝了Microsoft VC ++編譯器,所以python能夠編譯任何依賴項。您能夠從Visual Studio獲取編譯器。下載安裝程序,而後在列表中選擇VC ++ Build工具。docker
NLU Pipeline Dependenciesshell
Rasa NLU具備用於識別意圖和實體的不一樣組件,其中大多數具備一些額外的依賴性。json
當您訓練NLU模型時,Rasa將檢查是否安裝了全部必需的依賴項,並告訴您是否缺乏任何依賴項。選擇管道的頁面將幫助您選擇要使用的管道。後端
若是你想確保爲你可能須要的任何組件安裝了依賴項,而且你不介意附加的依賴項,你可使用以下命令安裝全部依賴項。
pip install -r alt_requirements/requirements_full.txt 複製代碼
入門:使用spaCy
預訓練向量
pretrained_embeddings_spacy
管道結合了一些不一樣的庫,是一種流行的選擇。有關更多信息,請查看spaCy文檔。 能夠經過下面的命令安裝:
pip install rasa[spacy]
python -m spacy download en_core_web_md
python -m spacy link en_core_web_md en
複製代碼
該命令會安裝Rasa NLU以及spacy和它的英語語言模型。咱們建議使用最新的「medium」大小的模型(_md),代替spacy默認的最小的en_core_web_sm
模型。小的模型須要更少的內存來運行,但有時會下降意圖分類的性能。
第一種選擇:Tensorflow
爲了使用supervised_embeddings
管道,須要安裝tensorflow
,爲了實現實體識別須要安裝sklearn-crfsuite
庫。運行下面的命令:
pip install rasa
複製代碼
第二種選擇:MITIE
後端使用MITIE
對於小型數據集更適用,若是你有數百個例子,訓練時間可能會比較長。將來咱們可能會棄用MITIE。 首先,運行:
pip install git+https://github.com/mit-nlp/MITIE.git
pip install rasa[mitie]
複製代碼
下載MITIE模型文件total_word_feature_extractor.dat
。
MITIE的完整pipeline:
language: "en"
pipeline:
- name: "MitieNLP"
model: "data/total_word_feature_extractor.dat"
- name: "MitieTokenizer"
- name: "MitieEntityExtractor"
- name: "EntitySynonymMapper"
- name: "RegexFeaturizer"
- name: "MitieFeaturizer"
- name: "SklearnIntentClassifier"
複製代碼
單獨使用MITIE訓練可能會很慢,但你可使用以下配置:
language: "en"
pipeline:
- name: "MitieNLP"
model: "data/total_word_feature_extractor.dat"
- name: "MitieTokenizer"
- name: "MitieEntityExtractor"
- name: "EntitySynonymMapper"
- name: "RegexFeaturizer"
- name: "MitieIntentClassifier"
複製代碼
本頁介紹了使用Rasa構建助手的基礎知識,並顯示了Rasa項目的結構。你能夠在這裏測試它而不須要安裝任何東西。您還能夠安裝Rasa並在命令行中進行操做。
在這個教程中,你將創建一個簡單、友好的助手,它會問你在作什麼併發送給你一個有趣的圖片讓你振做起來。
1. 建立一個新項目
第一步是建立一個新的Rasa項目,運行:
rasa init --no-prompt
複製代碼
rasa init
命令建立Rasa項目所需的全部文件,並在一些示例數據上訓練一個簡單的bot。若是省略--no-prompt
標誌,將會詢問有關您但願如何設置項目的一些問題。 將建立如下文件:
文件 | 含義 |
---|---|
__init__py |
一個空文件,幫助python找到actions |
actions.py |
自定義actions的代碼 |
config.yml ‘*’ |
NLU和Core模型的配置 |
credentials.yml |
鏈接其餘服務的細節 |
data/nlu.md ‘*’ |
NLU訓練數據 |
data/stories.md ‘*’ |
stories |
domain.yml ‘*’ |
助手的domain |
endpoints.yml |
鏈接通道的細節 |
model/<timestamp>.tar.gz |
初始化模型 |
標‘*’
的是重要的文件。
2. 查看訓練數據
Rasa助手的第一部分是NLU模型。NLU表明天然語言理解,這意味着將用戶消息轉換爲結構化數據。要使用Rasa執行此操做,須要提供訓練示例,以說明Rasa應如何理解用戶消息,而後經過向其展現這些示例來訓練模型。
## intent:greet
- hey
- hello
- hi
- good morning
- good evening
- hey there
## intent:goodbye
- bye
- goodbye
- see you around
- see you later
複製代碼
以##
開頭的行定義了意圖的名稱,這些意圖是具備相同含義的消息組。當您的用戶向助理髮送新的,看不見的消息時,Rasa的工做將是預測正確的意圖。您能夠在「訓練數據格式」中找到數據格式的全部詳細信息。
3. 定義你的模型配置
配置文件定義模型將使用的NLU和Core組件。在此示例中,您的NLU模型將使用supervised_embeddings管道。您能夠在此處瞭解不一樣的NLU管道。 咱們來看看你的模型配置文件:
cat config.yml
配置以下:
# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: en
pipeline: supervised_embeddings
# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
policies:
- name: MemoizationPolicy
- name: KerasPolicy
- name: MappingPolicy
複製代碼
關鍵字language
和pipeline
指定了NLU模型如何創建。policy
定義了Core模型使用的決策信息。
4. 寫你的第一個stories
在此階段,您將教您的助手如何回覆您的消息,這稱爲對話管理,由您的Core模型處理。 Core模型以訓練「故事」的形式從真實的會話數據中學習。故事是用戶和助手之間的真實對話。具備意圖和實體的行反映了用戶的輸入,操做名稱顯示了助手應該作出的響應。
如下是簡單對話的示例。用戶打招呼,助理回答問好。這就是它看起來像一個故事:
## story1
* greet
- utter_greet
複製代碼
以 -
開頭的行是助手採起的行動。在本教程中,咱們的全部操做都是發送回用戶的消息,例如utter_greet
,但一般,操做能夠執行任何操做,包括調用API和與外部世界交互。
運行下面的命令行查看data/stories.md
的示例:
## happy path
* greet
- utter_greet
* mood_great
- utter_happy
## sad path 1
* greet
- utter_greet
* mood_unhappy
- utter_cheer_up
- utter_did_that_help
* affirm
- utter_happy
複製代碼
5. 定義domain
domain定義了您的助手所處的領域:它應該得到的用戶輸入,應該可以預測的操做,如何響應以及要存儲的信息。咱們助手的domain保存在名爲domain.yml
的文件中:
intents:
- greet
- goodbye
- affirm
- deny
- mood_great
- mood_unhappy
actions:
- utter_greet
- utter_cheer_up
- utter_did_that_help
- utter_happy
- utter_goodbye
templates:
utter_greet:
- text: "Hey! How are you?"
utter_cheer_up:
- text: "Here is something to cheer you up:"
image: "https://i.imgur.com/nGF1K8f.jpg"
utter_did_that_help:
- text: "Did that help you?"
複製代碼
名稱 | 含義 |
---|---|
intents | things you expect users to say |
actions | things your assistant can do and say |
templates | template strings for the things your assistant can say |
這如何組合在一塊兒?Rasa Core的工做是選擇在對話的每一個步驟執行的正確操做。 在這種狀況下,咱們的操做只是向用戶發送消息,這些簡單的話語動做是域中以utter_
開頭的動做。助理將根據模板部分的模板回覆消息。請參閱自定義操做以構建不只僅是發送消息的操做。
6. 訓練模型
不管什麼時候咱們添加新的NLU或Core數據,或更新domain或配置,咱們都須要在咱們的示例stories和NLU數據上從新訓練神經網絡。爲此,請運行如下命令。此命令將調用Rasa Core和NLU訓練功能,並將訓練好的模型存儲到模型/目錄中。若是數據或配置發生變化,該命令將自動僅從新訓練不一樣的模型部件。
rasa train
複製代碼
rasa train
命令將查找NLU和Core數據,並將訓練組合模型。
7. 和你的助手交談
恭喜!🚀你剛剛創建了一個徹底由機器學習驅動的助手。下一步就是嘗試一下!若是您在本地計算機上關注本教程,請經過運行如下方式與助理通話:
rasa shell
複製代碼
您還可使用Rasa X收集更多對話並改進助手。
命令行接口(CLI)爲您提供易於記憶的常見任務命令。
命令 | 做用 |
---|---|
rasa_init | 建立一個新的項目,包含示例訓練數據,動做和配置文件 |
rasa_train | 使用NLU數據和stories訓練模型,保存模型在./models 中 |
rasa interactive | 經過交談開啓一個新的交互學習會話來建立新的訓練數據 |
rasa shell | 加載訓練模型,與助手經過命令行交談 |
rasa run | 使用訓練的模型開啓一個Rasa服務 |
rasa run actions | 使用Rasa SDK開啓action服務器 |
rasa visualize | 可視化stories |
rasa test | 使用測試NLU數據和故事來測試訓練好的Rasa模型 |
rasa data split nlu | 根據指定的百分比執行NLU數據的拆分 |
rasa data convert nlu | 在不一樣格式之間轉換NLU訓練數據 |
rasa x | 在本地啓動Rasa X |
rasa -h | 顯示全部可用命令 |
建立新項目
單個命令爲您設置一個完整的項目,其中包含一些示例訓練數據。
rasa init
複製代碼
包含如下文件:
.
├── __init__.py
├── actions.py
├── config.yml
├── credentials.yml
├── data
│ ├── nlu.md
│ └── stories.md
├── domain.yml
├── endpoints.yml
└── models
└── <timestamp>.tar.gz
複製代碼
rasa init
命令會詢問你是否想要使用數據訓練一個初始模型,若是回答no,model目錄將爲空。
訓練模型
命令:
rasa train
複製代碼
該命令訓練Rasa模型,該模型結合了Rasa NLU和Rasa Core模型。若是您只想訓練NLU或Core模型,您能夠運行rasa train nlu
或rasa train core
。可是,若是訓練數據和配置沒有改變,Rasa將自動跳過訓練Core或NLU。
rasa trian
將存儲訓練好的模型到--out
指定的目標下。模型的名字默認是<timestamp>.tar.gz
。若是想要本身命名,能夠經過--fixed-model-name
來指定。
如下參數可用於配置訓練過程:
usage: rasa train [-h] [-v] [-vv] [--quiet] [--data DATA [DATA ...]]
[-c CONFIG] [-d DOMAIN] [--out OUT]
[--augmentation AUGMENTATION] [--debug-plots]
[--dump-stories] [--fixed-model-name FIXED_MODEL_NAME]
[--force]
{core,nlu} ...
positional arguments:
{core,nlu}
core Trains a Rasa Core model using your stories.
nlu Trains a Rasa NLU model using your NLU data.
optional arguments:
-h, --help show this help message and exit
--data DATA [DATA ...]
Paths to the Core and NLU data files. (default:
['data'])
-c CONFIG, --config CONFIG
The policy and NLU pipeline configuration of your bot.
(default: config.yml)
-d DOMAIN, --domain DOMAIN
Domain specification (yml file). (default: domain.yml)
--out OUT Directory where your models should be stored.
(default: models)
--augmentation AUGMENTATION
How much data augmentation to use during training.
(default: 50)
--debug-plots If enabled, will create plots showing checkpoints and
their connections between story blocks in a file
called `story_blocks_connections.html`. (default:
False)
--dump-stories If enabled, save flattened stories to a file.
(default: False)
--fixed-model-name FIXED_MODEL_NAME
If set, the name of the model file/directory will be
set to the given name. (default: None)
--force Force a model training even if the data has not
changed. (default: False)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
使用
rasa train
命令訓練模型時,確保Core和NLU的訓練數據存在。若是僅存在一種模型類型的訓練數據,則該命令將根據提供的訓練文件自動回退到rasa train nlu
或rasa train core
。
交互式學習
要與助理開始交互式學習會話,請運行:
rasa interactive
複製代碼
若是使用--model
參數指定訓練模型,則使用提供的模型啓動交互式學習過程。若是沒有指定模型,rasa interactive
將訓練一個新的Rasa模型,若是沒有其餘目錄傳遞給--data
標誌,則其數據位於data /
中。在訓練初始模型以後,交互式學習會話開始。若是訓練數據和配置沒有改變,將跳過訓練。
rasa interactive
全部參數列表以下:
usage: rasa interactive [-h] [-v] [-vv] [--quiet] [-m MODEL]
[--data DATA [DATA ...]] [--skip-visualization]
[--endpoints ENDPOINTS] [-c CONFIG] [-d DOMAIN]
[--out OUT] [--augmentation AUGMENTATION]
[--debug-plots] [--dump-stories] [--force]
{core} ... [model-as-positional-argument]
positional arguments:
{core}
core Starts an interactive learning session model to create
new training data for a Rasa Core model by chatting.
Uses the 'RegexInterpreter', i.e. `/<intent>` input
format.
model-as-positional-argument
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: None)
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: None)
--data DATA [DATA ...]
Paths to the Core and NLU data files. (default:
['data'])
--skip-visualization Disable plotting the visualization during interactive
learning. (default: False)
--endpoints ENDPOINTS
Configuration file for the model server and the
connectors as a yml file. (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
Train Arguments:
-c CONFIG, --config CONFIG
The policy and NLU pipeline configuration of your bot.
(default: config.yml)
-d DOMAIN, --domain DOMAIN
Domain specification (yml file). (default: domain.yml)
--out OUT Directory where your models should be stored.
(default: models)
--augmentation AUGMENTATION
How much data augmentation to use during training.
(default: 50)
--debug-plots If enabled, will create plots showing checkpoints and
their connections between story blocks in a file
called `story_blocks_connections.html`. (default:
False)
--dump-stories If enabled, save flattened stories to a file.
(default: False)
--force Force a model training even if the data has not
changed. (default: False)
複製代碼
與你的助手交談
使用以下命令:
rasa shell
複製代碼
應該用於與機器人交互的模型能夠由--model
指定。若是使用僅NLU模型啓動shell,則rasa shell
容許您獲取在命令行上鍵入的任何文本的intent和實體。若是您的模型包含通過訓練的Core模型,您能夠與機器人聊天,並查看機器人預測的下一步操做。若是您已經訓練了一個組合的Rasa模型,可是想要查看模型從文本中提取的意圖和實體,您可使用命令rasa shell nlu
。
要增長調試的日誌記錄級別,請運行:
rasa shell --debug
複製代碼
rasa shell
的全部選項列表以下:
usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
[--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--credentials CREDENTIALS] [--connector CONNECTOR]
[--jwt-secret JWT_SECRET] [--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]
positional arguments:
{nlu}
nlu Interprets messages on the command line using your NLU
model.
model-as-positional-argument
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: None)
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: models)
--log-file LOG_FILE Store logs in specified file. (default: None)
--endpoints ENDPOINTS
Configuration file for the model server and the
connectors as a yml file. (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
Server Settings:
-p PORT, --port PORT Port to run the server at. (default: 5005)
-t AUTH_TOKEN, --auth-token AUTH_TOKEN
Enable token based authentication. Requests need to
provide the token to be accepted. (default: None)
--cors [CORS [CORS ...]]
Enable CORS for the passed origin. Use * to whitelist
all origins. (default: None)
--enable-api Start the web server API in addition to the input
channel. (default: False)
--remote-storage REMOTE_STORAGE
Set the remote location where your Rasa model is
stored, e.g. on AWS. (default: None)
Channels:
--credentials CREDENTIALS
Authentication credentials for the connector as a yml
file. (default: None)
--connector CONNECTOR
Service to connect to. (default: None)
JWT Authentication:
--jwt-secret JWT_SECRET
Public key for asymmetric JWT methods or shared
secretfor symmetric methods. Please also make sure to
use --jwt-method to select the method of the
signature, otherwise this argument will be ignored.
(default: None)
--jwt-method JWT_METHOD
Method used for the signature of the JWT
authentication payload. (default: HS256)
複製代碼
啓動服務器
要啓動運行Rasa模型的服務器,請運行:
rasa run
複製代碼
下面的參數能夠用來配置你的Rasa服務器
usage: rasa run [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
[--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{actions} ... [model-as-positional-argument]
positional arguments:
{actions}
actions Runs the action server.
model-as-positional-argument
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: None)
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: models)
--log-file LOG_FILE Store logs in specified file. (default: None)
--endpoints ENDPOINTS
Configuration file for the model server and the
connectors as a yml file. (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
Server Settings:
-p PORT, --port PORT Port to run the server at. (default: 5005)
-t AUTH_TOKEN, --auth-token AUTH_TOKEN
Enable token based authentication. Requests need to
provide the token to be accepted. (default: None)
--cors [CORS [CORS ...]]
Enable CORS for the passed origin. Use * to whitelist
all origins. (default: None)
--enable-api Start the web server API in addition to the input
channel. (default: False)
--remote-storage REMOTE_STORAGE
Set the remote location where your Rasa model is
stored, e.g. on AWS. (default: None)
Channels:
--credentials CREDENTIALS
Authentication credentials for the connector as a yml
file. (default: None)
--connector CONNECTOR
Service to connect to. (default: None)
JWT Authentication:
--jwt-secret JWT_SECRET
Public key for asymmetric JWT methods or shared
secretfor symmetric methods. Please also make sure to
use --jwt-method to select the method of the
signature, otherwise this argument will be ignored.
(default: None)
--jwt-method JWT_METHOD
Method used for the signature of the JWT
authentication payload. (default: HS256)
複製代碼
開啓Action服務器
使用以下命令運行:
rasa run actions
複製代碼
下面的參數可用於調整服務器設置:
usage: rasa run actions [-h] [-v] [-vv] [--quiet] [-p PORT]
[--cors [CORS [CORS ...]]] [--actions ACTIONS]
optional arguments:
-h, --help show this help message and exit
-p PORT, --port PORT port to run the server at (default: 5055)
--cors [CORS [CORS ...]]
enable CORS for the passed origin. Use * to whitelist
all origins (default: None)
--actions ACTIONS name of action package to be loaded (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
可視化你的stories
rasa visualize
複製代碼
一般,訓練的stories位於data
目錄下是可視的。如何你的stories存儲在其餘地方,使用--stories
指定他們的位置。
參數以下:
usage: rasa visualize [-h] [-v] [-vv] [--quiet] [-d DOMAIN] [-s STORIES]
[-c CONFIG] [--out OUT] [--max-history MAX_HISTORY]
[-u NLU]
optional arguments:
-h, --help show this help message and exit
-d DOMAIN, --domain DOMAIN
Domain specification (yml file). (default: domain.yml)
-s STORIES, --stories STORIES
File or folder containing your training stories.
(default: data)
-c CONFIG, --config CONFIG
The policy and NLU pipeline configuration of your bot.
(default: config.yml)
--out OUT Filename of the output path, e.g. 'graph.html'.
(default: graph.html)
--max-history MAX_HISTORY
Max history to consider when merging paths in the
output graph. (default: 2)
-u NLU, --nlu NLU File or folder containing your NLU data, used to
insert example messages into the graph. (default:
None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
會生成一個graph.html
文件在當前路徑下。
在測試數據上驗證模型
運行:
rasa test
複製代碼
使用--model
指定模型。 參數以下:
usage: rasa test [-h] [-v] [-vv] [--quiet] [-m MODEL] [-s STORIES]
[--max-stories MAX_STORIES] [--e2e] [--endpoints ENDPOINTS]
[--fail-on-prediction-errors] [--url URL]
[--evaluate-model-directory] [-u NLU] [--out OUT]
[--report [REPORT]] [--successes [SUCCESSES]]
[--errors ERRORS] [--histogram HISTOGRAM] [--confmat CONFMAT]
[-c CONFIG [CONFIG ...]] [--cross-validation] [-f FOLDS]
[-r RUNS] [-p PERCENTAGES [PERCENTAGES ...]]
{core,nlu} ...
positional arguments:
{core,nlu}
core Tests Rasa Core models using your test stories.
nlu Tests Rasa NLU models using your test NLU data.
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: models)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
Core Test Arguments:
-s STORIES, --stories STORIES
File or folder containing your test stories. (default:
data)
--max-stories MAX_STORIES
Maximum number of stories to test on. (default: None)
--e2e, --end-to-end Run an end-to-end evaluation for combined action and
intent prediction. Requires a story file in end-to-end
format. (default: False)
--endpoints ENDPOINTS
Configuration file for the connectors as a yml file.
(default: None)
--fail-on-prediction-errors
If a prediction error is encountered, an exception is
thrown. This can be used to validate stories during
tests, e.g. on travis. (default: False)
--url URL If supplied, downloads a story file from a URL and
trains on it. Fetches the data by sending a GET
request to the supplied URL. (default: None)
--evaluate-model-directory
Should be set to evaluate models trained via 'rasa train core --config <config-1> <config-2>'. All models
in the provided directory are evaluated and compared
against each other. (default: False)
NLU Test Arguments:
-u NLU, --nlu NLU File or folder containing your NLU data. (default:
data)
--out OUT Output path for any files created during the
evaluation. (default: results)
--report [REPORT] Output path to save the intent/entity metrics report.
(default: None)
--successes [SUCCESSES]
Output path to save successful predictions. (default:
None)
--errors ERRORS Output path to save model errors. (default:
errors.json)
--histogram HISTOGRAM
Output path for the confidence histogram. (default:
hist.png)
--confmat CONFMAT Output path for the confusion matrix plot. (default:
confmat.png)
-c CONFIG [CONFIG ...], --config CONFIG [CONFIG ...]
Model configuration file. If a single file is passed
and cross validation mode is chosen, cross-validation
is performed, if multiple configs or a folder of
configs are passed, models will be trained and
compared directly. (default: None)
複製代碼
拆分Train Test訓練數據 要進行NLU數據的拆分,請運行:
rasa data split nlu
複製代碼
你能夠指定訓練數據,輸出目錄等,參數以下:
usage: rasa data split nlu [-h] [-v] [-vv] [--quiet] [-u NLU]
[--training-fraction TRAINING_FRACTION] [--out OUT]
optional arguments:
-h, --help show this help message and exit
-u NLU, --nlu NLU File or folder containing your NLU data. (default:
data)
--training-fraction TRAINING_FRACTION
Percentage of the data which should be in the training
data. (default: 0.8)
--out OUT Directory where the split files should be stored.
(default: train_test_split)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
此命令將嘗試在訓練和測試中保持意圖的比例相同。
在Markdown和JSON之間轉換數據
要將NLU數據從LUIS數據格式,WIT數據格式,Dialogflow數據格式,JSON或Markdown轉換爲JSON或Markdown,請運行:
rasa data convert nlu
複製代碼
能夠指定輸入文件,輸出文件,輸出格式等,參數以下:
usage: rasa data convert nlu [-h] [-v] [-vv] [--quiet] --data DATA --out OUT
[-l LANGUAGE] -f {json,md}
optional arguments:
-h, --help show this help message and exit
--data DATA Path to the file or directory containing Rasa NLU
data. (default: None)
--out OUT File where to save training data in Rasa format.
(default: None)
-l LANGUAGE, --language LANGUAGE
Language of data. (default: en)
-f {json,md}, --format {json,md}
Output format the training data should be converted
into. (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
啓動Rasa X
Rasa X是一個工具,可幫助您構建\改進和部署由Rasa框架提供支持的AI Assistants。您能夠在此處找到有關它的更多信息。
您能夠經過執行來本地啓動Rasa X:
rasa x
複製代碼
爲了可以啓動Rasa X,您須要安裝Rasa X,您須要進入Rasa項目。
默認狀況下,
Rasa X
在端口5002
上運行。使用參數--rasa-x-port
能夠將其更改成任何其餘端口。
如下參數可用於rasa x:
usage: rasa x [-h] [-v] [-vv] [--quiet] [-m MODEL] [--data DATA] [--no-prompt]
[--production] [--rasa-x-port RASA_X_PORT] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
[--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: models)
--data DATA Path to the file or directory containing stories and
Rasa NLU data. (default: data)
--no-prompt Automatic yes or default options to prompts and
oppressed warnings. (default: False)
--production Run Rasa X in a production environment. (default:
False)
--rasa-x-port RASA_X_PORT
Port to run the Rasa X server at. (default: 5002)
--log-file LOG_FILE Store logs in specified file. (default: None)
--endpoints ENDPOINTS
Configuration file for the model server and the
connectors as a yml file. (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
Server Settings:
-p PORT, --port PORT Port to run the server at. (default: 5005)
-t AUTH_TOKEN, --auth-token AUTH_TOKEN
Enable token based authentication. Requests need to
provide the token to be accepted. (default: None)
--cors [CORS [CORS ...]]
Enable CORS for the passed origin. Use * to whitelist
all origins. (default: None)
--enable-api Start the web server API in addition to the input
channel. (default: False)
--remote-storage REMOTE_STORAGE
Set the remote location where your Rasa model is
stored, e.g. on AWS. (default: None)
Channels:
--credentials CREDENTIALS
Authentication credentials for the connector as a yml
file. (default: None)
--connector CONNECTOR
Service to connect to. (default: None)
JWT Authentication:
--jwt-secret JWT_SECRET
Public key for asymmetric JWT methods or shared
secretfor symmetric methods. Please also make sure to
use --jwt-method to select the method of the
signature, otherwise this argument will be ignored.
(default: None)
--jwt-method JWT_METHOD
Method used for the signature of the JWT
authentication payload. (default: HS256)
複製代碼
消息處理
此圖顯示了使用Rasa構建的助手如何響應消息的基本步驟:
步驟以下:
Tracker
是跟蹤對話狀態的對象。它接收新消息進入的信息。Tracker
的當前狀態。Tracker
記錄。消息能夠是人類輸入的文本,也能夠是按鈕按下等結構化輸入。
若是你是在本地計算機(不是服務器)上進行測試,你須要使用ngrok。這會給你的機器一個domain名字讓Facebook, Slack等
知道消息發送到哪裏來到達你的本地機器。
爲了讓你的助手在消息傳遞平臺上可用,您須要在credentials.yml
文件中提供憑據。運行rasa init
時會建立一個示例文件,所以最簡單的方法是編輯該文件並在其中添加憑據 。如下是Facebook憑據的示例:
facebook:
verify: "rasa-bot"
secret: "3e34709d01ea89032asdebfe5a74518"
page-access-token: "EAAbHPa7H9rEBAAuFk4Q3gPKbDedQnx4djJJ1JmQ7CAqO4iJKrQcNT0wtD"
複製代碼
評估NLU模型
使用以下命令分離NLU的訓練和測試數據:
rasa data split nlu
複製代碼
使用NLU模型在測試用例上預測:
rasa test nlu -u test_set.md --model models/nlu-xxx.tar.gz
複製代碼
若是您不想建立單獨的測試集,仍可使用交叉驗證來估計模型的優化程度。爲此,請添加標誌--cross-validation
:
rasa test nlu -u data/nlu.md --config config.yml --cross-validation
複製代碼
該腳本的完整選項列表以下:
usage: rasa test nlu [-h] [-v] [-vv] [--quiet] [-m MODEL] [-u NLU] [--out OUT]
[--report [REPORT]] [--successes [SUCCESSES]]
[--errors ERRORS] [--histogram HISTOGRAM]
[--confmat CONFMAT] [-c CONFIG [CONFIG ...]]
[--cross-validation] [-f FOLDS] [-r RUNS]
[-p PERCENTAGES [PERCENTAGES ...]]
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Path to a trained Rasa model. If a directory is
specified, it will use the latest model in this
directory. (default: models)
-u NLU, --nlu NLU File or folder containing your NLU data. (default:
data)
--out OUT Output path for any files created during the
evaluation. (default: results)
--report [REPORT] Output path to save the intent/entity metrics report.
(default: None)
--successes [SUCCESSES]
Output path to save successful predictions. (default:
None)
--errors ERRORS Output path to save model errors. (default:
errors.json)
--histogram HISTOGRAM
Output path for the confidence histogram. (default:
hist.png)
--confmat CONFMAT Output path for the confusion matrix plot. (default:
confmat.png)
-c CONFIG [CONFIG ...], --config CONFIG [CONFIG ...]
Model configuration file. If a single file is passed
and cross validation mode is chosen, cross-validation
is performed, if multiple configs or a folder of
configs are passed, models will be trained and
compared directly. (default: None)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
Cross Validation:
--cross-validation Switch on cross validation mode. Any provided model
will be ignored. (default: False)
-f FOLDS, --folds FOLDS
Number of cross validation folds (cross validation
only). (default: 10)
Comparison Mode:
-r RUNS, --runs RUNS Number of comparison runs to make. (default: 3)
-p PERCENTAGES [PERCENTAGES ...], --percentages PERCENTAGES [PERCENTAGES ...]
Percentages of training data to exclude during
comparison. (default: [0, 25, 50, 75])
複製代碼
比較NLU管道 經過將多個管道配置(或包含它們的文件夾)傳遞給CLI,Rasa將在管道之間進行比較檢查。
rasa test nlu --config pretrained_embeddings_spacy.yml supervised_embeddings.yml
--nlu data/nlu.md --runs 3 --percentages 0 25 50 70 90
複製代碼
上例中的命令將根據數據建立訓練/測試集,而後屢次訓練每一個管道,其中0,25,50,70和90%的意圖數據從訓練集中排除。而後在測試集上評估模型,並記錄每一個排除百分比的f1-scores。該過程運行三次(即總共有3個測試集),而後使用f1-scores的平均值和標準誤差繪製圖表。 f1-score圖表 - 以及全部訓練/測試集,訓練模型,分類和錯誤報告將保存到名爲nlu_comparison_results
的文件夾中。
意圖分類
評估腳本將爲您的模型生成報告,混淆矩陣和置信度直方圖。
該報告記錄每一個意圖和實體的精確度,召回率和f1度量,並提供整體平均值。您可使用--report
參數將這些報告另存爲JSON文件。
混淆矩陣向您顯示哪些意圖被誤認爲是其餘意圖;任何錯誤預測的樣本都會被記錄並保存到名爲errors.json
的文件中,以便於調試。
腳本生成的直方圖容許您可視化全部預測的置信度分佈,其中正確和錯誤預測的量分別由藍色和紅色條顯示。提升訓練數據的質量會使藍色直方圖條向右移動,紅色直方圖條移動到圖的左側。
只有在評估測試集上的模型時,纔會建立混淆矩陣。在交叉驗證模式下,將不會生成混淆矩陣。
實體識別
CRFEntityExtractor
是您使用本身的數據訓練的惟一實體提取器,所以是惟一將被評估的實體提取器。若是您使用spaCy
或duckling
預訓練實體提取器,Rasa NLU將不會在評估中包含這些。
Rasa NLU將報告CRFEntityExtractor
通過培訓識別的每種實體類型的召回,精確度和f1度量。
實體得分
爲了評估實體提取,咱們應用一種簡單的基於標籤的方法。咱們不考慮BILOU
標記,而只考慮每一個標記的實體類型標記。對於像「亞歷山大廣場附近」這樣的位置實體,咱們指望標籤LOC LOC而不是基於BILOU的B-LOC L-LOC。咱們的方法在評估時更寬鬆,由於它獎勵部分提取而且不懲罰實體的分裂。
評估Core模型
rasa test core --stories test_stories.md --out results
複製代碼
將失敗的stories輸出在results/failed_stories.md
中。若是至少有一個動做被錯誤預測,咱們會將任何故事視爲失敗。
此外,這會將混淆矩陣保存到名爲results / story_confmat.pdf
的文件中。對於您domian的每一個操做,混淆矩陣會顯示操做的正確預測頻率以及預測錯誤操做的頻率。
腳本的全部選項列表以下:
usage: rasa test core [-h] [-v] [-vv] [--quiet] [-m MODEL [MODEL ...]]
[-s STORIES] [--max-stories MAX_STORIES] [--out OUT]
[--e2e] [--endpoints ENDPOINTS]
[--fail-on-prediction-errors] [--url URL]
[--evaluate-model-directory]
optional arguments:
-h, --help show this help message and exit
-m MODEL [MODEL ...], --model MODEL [MODEL ...]
Path to a pre-trained model. If it is a 'tar.gz' file
that model file will be used. If it is a directory,
the latest model in that directory will be used
(exception: '--evaluate-model-directory' flag is set).
If multiple 'tar.gz' files are provided, all those
models will be compared. (default: [None])
-s STORIES, --stories STORIES
File or folder containing your test stories. (default:
data)
--max-stories MAX_STORIES
Maximum number of stories to test on. (default: None)
--out OUT Output path for any files created during the
evaluation. (default: results)
--e2e, --end-to-end Run an end-to-end evaluation for combined action and
intent prediction. Requires a story file in end-to-end
format. (default: False)
--endpoints ENDPOINTS
Configuration file for the connectors as a yml file.
(default: None)
--fail-on-prediction-errors
If a prediction error is encountered, an exception is
thrown. This can be used to validate stories during
tests, e.g. on travis. (default: False)
--url URL If supplied, downloads a story file from a URL and
trains on it. Fetches the data by sending a GET
request to the supplied URL. (default: None)
--evaluate-model-directory
Should be set to evaluate models trained via 'rasa train core --config <config-1> <config-2>'. All models
in the provided directory are evaluated and compared
against each other. (default: False)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
比較策略Policy
選擇特定的策略配置,或選擇特定策略的超參數,您須要衡量Rasa Core將會歸納爲之前從未見過的對話的程度。特別是在項目的開始階段,你沒有不少真正的對話來用來訓練你的機器人,因此你不僅是想扔掉一些用做測試集。
Rasa Core有一些腳本可幫助您選擇和微調策略配置。一旦您滿意,您就能夠在完整數據集上訓練最終配置。要作到這一點,首先必須爲不一樣的策略訓練模型。建立兩個(或更多)配置文件,包括要比較的策略(每一個只包含一個策略),而後使用訓練腳本的比較模式訓練模型:
rasa train core -c config_1.yml config_2.yml \
-d domain.yml -s stories_folder --out comparison_models --runs 3 \
--percentages 0 5 25 50 70 95
複製代碼
低於提供的每一個policy配置,Rasa Core將進行屢次培訓,將0,5,25,50,70和95%的培訓故事排除在培訓數據以外。這是爲屢次運行完成的,以確保一致的結果。
訓練完成後,進行評估:
rasa test core -m comparison_models --stories stories_folder
--out comparison_results --evaluate-model-directory
複製代碼
這將評估訓練集上的每一個模型,並繪製一些圖表以顯示哪一個策略表現最佳。經過評估整套故事,您能夠衡量Rasa Core對預測故事的預測效果。
若是您不肯定要比較哪些策略,咱們建議您嘗試使用EmbeddingPolicy``和KerasPolicy
來查看哪一種策略更適合您。
這個訓練過程可能須要很長時間,因此咱們建議讓它在後臺運行,不能中斷。
端到端評估
Rasa容許您端到端地評估對話,運行測試對話並確保NLU和Core都能作出正確的預測。 爲此,您須要一些端到端格式的故事,其中包括NLU輸出和原始文本。這是一個例子:
## end-to-end story 1
* greet: hello
- utter_ask_howcanhelp
* inform: show me [chinese](cuisine) restaurants
- utter_ask_location
* inform: in [Paris](location)
- utter_ask_price
複製代碼
若是您將端到端故事保存爲名爲e2e_stories.md
的文件,則能夠經過運行如下命令來評估您的模型:
rasa test --stories e2e_stories.md --e2e
複製代碼
確保模型中的模型文件是組合
Core
和nlu
模型。若是它不包含NLU
模型,Core
將使用默認的RegexInterpreter
。
要驗證域文件,NLU數據或故事數據中是否存在任何錯誤,請運行驗證腳本。您可使用如下命令運行它:
rasa data validate
複製代碼
上面的腳本運行文件的全部驗證。如下是腳本的選項列表:
usage: rasa data validate [-h] [-v] [-vv] [--quiet] [-d DOMAIN] [--data DATA]
optional arguments:
-h, --help show this help message and exit
-d DOMAIN, --domain DOMAIN
Domain specification (yml file). (default: domain.yml)
--data DATA Path to the file or directory containing Rasa data.
(default: data)
Python Logging Options:
-v, --verbose Be verbose. Sets logging level to INFO. (default:
None)
-vv, --debug Print lots of debugging statements. Sets logging level
to DEBUG. (default: None)
--quiet Be quiet! Sets logging level to WARNING. (default:
None)
複製代碼
還能夠經過導入Validator
類來運行這些驗證,該類具備如下方法:
from_files()
:從字符串路徑中的文件建立實例。verify_intents()
:檢查domain文件中的intents列表包含NLU數據。verify_intents_in_stories()
:驗證stories中的意圖,檢查它們是否有效。verify_utterances()
:檢查domain文件,以肯定話語模板與操做下列出的話語之間的一致性。verify_utterances_in_stories()
:驗證stories中的話語,檢查它們是否有效。verify_all()
:運行上面的全部驗證。要使用這些函數,必須建立Validator對象並初始化記錄器。請參閱如下代碼:
import logging
from rasa import utils
from rasa.core.validator import Validator
logger = logging.getLogger(__name__)
utils.configure_colored_logging('DEBUG')
validator = Validator.from_files(domain_file='domain.yml',
nlu_data='data/nlu_data.md',
stories='data/stories.md')
validator.verify_all()
複製代碼
可使用通過訓練的Rasa模型運行一個簡單的HTTP服務器來處理請求:
rasa run -m models --enable-api --log-file out.log
複製代碼
此API公開的全部端點都記錄在HTTP API中。
-m
: 包含Rasa 模型的文件夾路徑--enable-api
: enable this additional API--log-file
: log文件路徑Rasa能夠經過三種不一樣的方式加載您的模型:
-m
加載指定的模型Rasa嘗試按上述順序加載模型,即若是沒有配置模型服務器和遠程存儲,它只會嘗試從本地存儲系統加載模型。
提醒: 確保經過限制對服務器的訪問(例如,使用防火牆)或啓用身份驗證方法來保護您的服務器:安全注意事項。
Note:
- 若是使用自定義操做,請確保操做服務器正在運行(請參閱啓動操做服務器)。若是您的操做在另外一臺計算機上運行,或者您沒有使用
Rasa SDK
,請確保更新您的endpoints.yml
文件。- 若是使用僅NLU模型啓動服務器,則不能調用全部可用端點。請注意,某些端點將返回409狀態代碼,由於須要通過培訓的Core模型來處理請求。
能夠配置HTTP服務器以從其餘URL獲取模型:
rasa run --enable-api --log-file out.log --endpoints my_endpoints.yml
複製代碼
模型服務器在端點配置(my_endpoints.yml
)中指定,您能夠在其中指定服務器URL Rasa按期查詢壓縮的Rasa模型:
models:
url: http://my-server.com/models/default@latest
wait_time_between_pulls: 10 # [optional](default: 100)
複製代碼
Note 若是要從服務器中僅拉取模型一次,請將
wait_time_between_pulls
設置爲None
。
Note 您的模型服務器必須提供壓縮的Rasa模型,並將
{「ETag」:<model_hash_string>}
做爲其標頭之一。若是此模型哈希發生更改,Rasa將僅下載新模型。
Rasa可能對您的模型服務器提出的示例請求以下所示:
curl --header "If-None-Match: d41d8cd98f00b204e9800998ecf8427e" http://my-server.com/models/default@latest
複製代碼
能夠配置Rasa服務器以從遠程存儲中獲取模型:
rasa run -m 20190506-100418.tar.gz --enable-api --log-file out.log --remote-storage aws
複製代碼
該模型將下載並存儲在本地存儲系統的臨時目錄中。
咱們建議不要將Rasa服務器暴露給外部世界,而是經過專用鏈接(例如,在docker容器之間)從後端鏈接到它。 然而,內置了兩種身份驗證方法:
--auth-token thisismysecret
傳遞令牌:rasa run \
-m models \
--enable-api \
--log-file out.log \
--auth-token thisismysecret
複製代碼
請求應該傳遞令牌,在咱們的案例中是thisismysecret
,做爲參數:curl -XGET localhost:5005/conversations/default/tracker?token=thisismysecret
複製代碼
--jwt-secret thisismysecret
啓用基於JWT的身份驗證。對服務器的請求須要在使用此密鑰和HS25
6算法簽名的Authorization
標頭中包含有效的JWT令牌。 用戶必須具備username
和role
屬性。若是role是admin
,則能夠訪問全部端點。若是role
是user
,則只有sender_id
與用戶的username匹配時才能訪問具備sender_id
參數的端點。rasa run \
-m models \
--enable-api \
--log-file out.log \
--jwt-secret thisismysecret
複製代碼
請求應該設置正確的JWT標頭:"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ"
"zdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIi"
"wiaWF0IjoxNTE2MjM5MDIyfQ.qdrr2_a7Sd80gmCWjnDomO"
"Gl8eZFVfKXA6jhncgRn-I"
複製代碼
要將Rasa鏈接到其餘端點,您能夠在YAML
文件中指定端點配置。而後使用標誌--endpoints <path to endpoint configuration.yml>
運行Rasa。 例如:
rasa run \
--m <Rasa model> \
--endpoints <path to endpoint configuration>.yml
複製代碼
可使用$ {name of environment variable}
指定配置文件中的環境變量。而後,這些佔位符將替換爲環境變量的值。