在Node.js中使用LUIS
我們沒事好好的幹嘛去弄Node.js呢? 還會為了誰? 當然就是LUIS。
還記得它吧,我們在很多地方介紹過LUIS,因為它是我們玩chatbot時候做自然語言語意分析(NLP)的要角,如果你忘記了,可以參考…
使用LUIS,讓你的bot理解用戶輸入文字的意義
建立LUIS服務處裡自然語言辨識
使用C#開發Linebot(20) - 不寫一行code完成Linebot的LUIS串接
OK,chat bot寫著寫著,開始有各種不同語言的需求,所以Node.js中使用LUIS也是剛好而已。(後面還有Python在等著)
前面我們介紹過如何使用VS Code開發Node.js,其實重點是為了這一篇如何在node.js中呼叫LUIS服務,其實也很簡單,我們可以參考這篇裡面的程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config(); | |
var request = require('request'); | |
var querystring = require('querystring'); | |
function getLuisIntent(utterance) { | |
var endpoint = | |
"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/"; | |
// Set the LUIS_APP_ID environment variable | |
// to df67dcdb-c37d-46af-88e1-8b97951ca1c2, which is the ID | |
// of a public sample application. | |
var luisAppId = '!!!!!!!換成你的AppId!!!!!!!'; | |
// Set the LUIS_SUBSCRIPTION_KEY environment variable | |
// to the value of your Cognitive Services subscription key | |
var queryParams = { | |
"subscription-key": '!!!!!!!換成你的Key!!!!!!!', | |
"timezoneOffset": "0", | |
"verbose": true, | |
"q": utterance | |
} | |
var luisRequest = | |
endpoint + luisAppId + | |
'?' + querystring.stringify(queryParams); | |
request(luisRequest, | |
function (err, | |
response, body) { | |
if (err) | |
console.log(err); | |
else { | |
var data = JSON.parse(body); | |
console.log(`Query: ${data.query}`); | |
console.log(`Top Intent: ${data.topScoringIntent.intent}`); | |
console.log('Intents:'); | |
console.log(data.intents); | |
} | |
}); | |
} | |
// Pass an utterance to the sample LUIS app | |
getLuisIntent('turn on the left light'); |
我稍微改了一下,主要是LUIS的app id與Key要換成你自己的(原本程式碼裡面採用.env環境變數,為了說明方便,這邊就先寫死了):
上圖中的App id和Key我換成了一個我訓練好的點餐服務LUIS App,所以我把 q 打成『我要大亨堡』,別忘了,這段程式碼要能運行,你還得用npm裝幾個套件:
完成後,試著按下F5在VS Code中執行app.js,結果如下:
成功的呼叫LUIS服務取得最可能的Intent囉…
留言