Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use nodejs BOT SDK to develop question and answer skill templates

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces how to use nodejs BOT SDK to develop question-and-answer skill templates, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Question and answer skills template

Q & A skills template is designed for Q & A skills, such as knowledge Q & A, life common sense questions and so on. This article describes how to quickly build question and answer skills from the interaction and deployment of question and answer skills.

The interaction Model of question and answer skill template

Question-and-answer skills interact with users by selecting a question from the list of question banks and providing four options, one of which is correct. The user answers the question by saying the order of the correct options.

The following takes the question and answer skills of ancient poetry as an example to describe the interaction process between question and answer skills and users. The skill selects a poem from the list of ancient poems and asks the user to name the author of the poem, and then read out the four author options in turn. The user says the correct order of the author's options, and the skill records the user's score when the answer is correct. The process of skill interaction is as follows:

Users: open the question and answer of ancient poetry

Skills: [skills welcome]. Start answering the questions. The first question: who is the author of the wild weeds growing in chaos in Guyuan every year when spring comes to flourish and autumn comes to withered and yellow? 1, Li Bai 2, Bai Juyi 3, du Fu 4, Liu Zongyuan

User: second

Skill: get one point for correct answer. The current score is one point. Question number two.

The skill of selecting questions from the question bank can put an end to the repetition of questions and the repetition of answers. Developers only need to update the list of topics and the corresponding skill configuration information to generate new skills and publish them on the DuerOS DBP platform. The question bank is stored as follows, in which the correct answer needs to be placed in the first place of the answer in the following format.

{'question': ['correct answer', 'wrong answer',],}

The above examples of questions and answers in ancient poems are shown in the question bank as follows:

The first question: who is the author of the wild weeds growing in chaos in Guyuan every spring and autumn? ['Bai Juyi','Li Bai','du Fu', 'Liu Zongyuan', question 2: the sun is setting against the mountains, and the Yellow River flows toward the sea. ['ascend the Stork Tower',',],}

Among them, the correct answers "Bai Juyi" and "climbing the Stork Tower" are placed in the first place, but when giving questions to users, the order of the options will be adjusted.

Instructions for the use of the template:

There must be a correct answer in the answer.

The answer options for each question can be 3, 4, 5, and there is no limit to the total number of options.

Each question must be answered by the option serial number, for example, the user must say "first" and "second", and cannot use "yes", "right", "wrong", "no" and so on.

The process of using templates to develop skills

Note that the following process of creating new skills and configuring intentions can be achieved by importing http://dbp-cfc.cdn.bcebos.com/download/trivia.zip on the skills platform-> create skills-- > reference skills-- > Import skills page.

New skills

For more information on creating new skills, see Custom skill creation.

Configuration intention

For details of intention configuration, see intent, common expressions and slots

The question and answer skill template needs to create two intentions, namely, the intention to answer the question and the intention to restart the question and answer. The intention to answer the question is shown in the following figure:

The intention to restart the question and answer is shown in the following figure:

Configure skill service deployment

The question and answer skills template uses CFC to deploy skills services. For more information on deploying skill services using CFC, please see Baidu Cloud CFC.

Modify CFC function code

The question and answer skills template uses questions.js to configure the question bank. Developers need to download the complete zip package of the skill CFC function to develop locally, and upload the function zip package for release after the development is completed. The specific process is as follows:

In the CFC console, create a function through the template, and select the node.js DuerOS Bot SDK template

After the function is generated, click the download complete ZIP package link in the function console to download the package.

Extract the package locally

Copy the https://github.com/dueros/bot-sdk-node.js/blob/master/samples/trivia/questions.js file to the package folder

Replace the index.js file in the package folder with https://github.com/dueros/bot-sdk-node.js/blob/master/samples/trivia/index.js

Repackage all files in the package folder into zip files

Upload the zip package in the function console and save it

For instructions on CFC operation, please see function calculation CFC.

The complete code const Bot = require ('bot-sdk'); const privateKey = require (". / rsaKeys.js") .privateKey Const question_list = [{'far up the mountain and rock path is oblique, there are people in the depths of Baiyun': ['correct','du Fu', 'Bai Juyi','Li Bai',}, {'the weeds on the ancient plain grow at random Every spring comes luxuriant and autumn comes withered yellow: ['correct','du Fu', 'Bai Juyi','Li Bai',}, {'look up at the bright moon in the sky Miss his hometown with his head down: ['correct','du Fu', 'Bai Juyi','Li Bai',}, {'farmers' hard hoe and sweat drop into the soil under Hexia at noon': ['correct','du Fu', 'Bai Juyi','Li Bai',],} {'the sun is setting along the mountains The Yellow River flows to the sea to the east: ['correct','du Fu', 'Bai Juyi','Li Bai',}, {'Li Bai is preparing to travel by boat Suddenly I heard the singing with feet as the beat on the shore: ['correct','du Fu', 'Bai Juyi','Li Bai',}, {'across the side of the winding mountain is a steep peak There are thousands of different ways to see from far and low: ['correct','du Fu', 'Bai Juyi','Li Bai',}, {'everyone will die Let me keep my loyalty in the history books: [Wen Tianxiang, du Fu, Bai Juyi, Li Bai,] / / define the number of questions in a round of Q & A const GAME_LENGTH = 5 this.waitAnswer / define the number of answers to each question const ANSWER_COUNT = 3 * * class InquiryBot extends Bot {constructor (postData) {super (postData); this.addLaunchHandler () = > {question (); let speechOutput = 'Welcome to the Ancient Poetry Q & A. I will read two ancient poems and give you the names of three poets. I need you to tell me which one is the right author.' ; / / initialize the list of questions in the round and the first question let repromptText = this.startNewGame (); let card = new Bot.Card.TextCard (repromptText) Return {card: card, outputSpeech: speechOutput + repromptText};}); this.addSessionEndedHandler (() = > {this.endSession () Return {outputSpeech: 'Thank you for using!'}); this.addIntentHandler ('answer_intent', () = > {this.waitAnswer (); / / make sure the user's answer let theAnswer = this.getSlot (' theAnswer') is obtained If (! theAnswer) {this.nlu.ask ('theAnswer'); return {outputSpeech:' which is your answer?' };} / / get relevant information in session let questionsList = this.getSessionAttribute ('questionsList'); let score = this.getSessionAttribute (' score'); let currentQuestionIndex = this.getSessionAttribute ('currentQuestionIndex'); let correctAnswerIndex = this.getSessionAttribute (' correctAnswerIndex'); let gameQuestions = this.getSessionAttribute ('gameQuestions') Let correctAnswerText = this.getSessionAttribute ('correctAnswerText'); let speechOutput =''; if (theAnswer = = correctAnswerIndex) {score + = 1; speechOutput = 'get a point if the answer is correct. Current score:'+ score +'. ;} else {speechOutput = 'Sorry, wrong answer. The correct answer is'+ correctAnswerText +'. Current score:'+ score +'. ;} / / reaching the last question, the user chooses to restart the round or quit the skill if (currentQuestionIndex = = GAME_LENGTH-1) {speechOutput + ='is already the last question. You can say start over to continue to answer the question, or withdraw from the skill.' Return {outputSpeech: speechOutput};} / / get the next information currentQuestionIndex + = 1; correctAnswerIndex = Math.floor (Math.random () * (ANSWER_COUNT)); let spokenQuestion = Object.keys (SecretsList [gameQuestions [currentQuestionIndex]) [0] Let roundAnswers = this.populateRoundAnswers (gameQuestions, currentQuestionIndex,correctAnswerIndex,questionsList); let questionIndexForSpeech = currentQuestionIndex + 1; let repromptText ='th'+ questionIndexForSpeech + 'question:\ n' + spokenQuestion +'\ nquestions; for (let I = 0; I

< ANSWER_COUNT; i += 1) { repromptText += `${i + 1}. ${roundAnswers[i]}. `; } speechOutput += repromptText; let currentQuestion = questionsList[gameQuestions[currentQuestionIndex]]; this.setSessionAttribute('speechOutput',speechOutput); this.setSessionAttribute('currentQuestionIndex',currentQuestionIndex); this.setSessionAttribute('correctAnswerIndex',correctAnswerIndex + 1); this.setSessionAttribute('gameQuestions',gameQuestions); this.setSessionAttribute('questionsList',questionsList); this.setSessionAttribute('score',score); this.setSessionAttribute('correctAnswerText',currentQuestion[Object.keys(currentQuestion)[0]][0]); let card = new Bot.Card.TextCard(repromptText); return { card: card, outputSpeech: speechOutput }; }); //重新开始答题,得分清零 this.addIntentHandler('newGame_intent', () =>

{this.waitAnswer (); / / initialize the list of questions in the round and the first question let repromptText = this.startNewGame (); let card = new Bot.Card.TextCard (repromptText) Return {card: card, outputSpeech:'OK, start over.' + repromptText};}) / * * get user input that has not been parsed by intention, and do relevant processing * default intention https://developer.dueros.baidu.com/didp/doc/dueros-bot-platform/dbp-nlu/defaultIntent_markdown * / this.addIntentHandler ('ai.dueros.common.default_intent', () = > {this.waitAnswer ()) Return {outputSpeech: 'you can tell me which one to tell me your answer. You can also say start playing again, or withdraw from the game.' };});} / * obtain the new round of question list and corresponding information, and store the information in session * * @ return new round of answering questions * / startNewGame () {let questionsList = question_list; let gameQuestions = this.populateGameQuestions (questionsList) Let correctAnswerIndex = Math.floor (Math.random () * (ANSWER_COUNT)); console.log (correctAnswerIndex); let roundAnswers = this.populateRoundAnswers (gameQuestions, 0gramme AnswerIndex); let currentQuestionIndex = 0; let spokenQuestion = Object.keys [gameQuestions [currentQuestionIndex]) [0] Let repromptText = 'question 1:\ n' + spokenQuestion +'\ nquestions; for (let I = 0; I

< ANSWER_COUNT; i += 1) { repromptText += `${i + 1}. ${roundAnswers[i]}. `; } let currentQuestion = questionsList[gameQuestions[currentQuestionIndex]]; this.setSessionAttribute('currentQuestionIndex',currentQuestionIndex); this.setSessionAttribute('correctAnswerIndex',correctAnswerIndex + 1); this.setSessionAttribute('gameQuestions',gameQuestions); this.setSessionAttribute('questionsList',questionsList); this.setSessionAttribute('score',0); this.setSessionAttribute('correctAnswerText',currentQuestion[Object.keys(currentQuestion)[0]][0]); return repromptText; } /** * 从问题列表中随机抽取问题。问题个数由变量GAME_LENGTH定义 * @param {list} translatedQuestions 所有问题列表 * @return 问题id列表 */ populateGameQuestions(translatedQuestions) { let gameQuestions = []; let indexList = []; let index = translatedQuestions.length; if (GAME_LENGTH >

Index) {throw new Error ('Invalid Game Length.');} for (let I = 0; I < translatedQuestions.length; I + = 1) {indexList.push (I);} for (let j = 0; j < GAME_LENGTH; j + = 1) {let rand = Math.floor (Math.random () * index) Index-= 1; let temp = indexList [index]; indexList [index] = indexList [rand]; indexList [rand] = temp; gameQuestions.push (indexList [index]);} return gameQuestions;} / * randomly extract questions from the question list. The number of questions is defined by the variable GAME_LENGTH * @ param {list} gameQuestionIndexes question list id list * @ param {int} currentQuestionIndex current question Index * @ param {int} correctAnswerTargetLocation current question answer Index * @ param {list} translatedQuestions all question list * @ return current question answer list * / populateRoundAnswers (gameQuestionIndexes,currentQuestionIndex,correctAnswerTargetLocation,translatedQuestions) {const answers = [] Const translatedQuestion = translatedQuestionIndexes [currentQuestionIndex]; const answersCopy = translatedQuestion [Object.keys (translatedQuestion) [0]] .slice (); let index = answersCopy.length; if (index < ANSWER_COUNT) {throw new Error ('Not enough answers for question.');} / disrupt the order of answers to the current question for (let j = 1) J < answersCopy.length; j + = 1) {const rand = Math.floor (Math.random () * (index-1)) + 1; index-= 1; const swapTemp1 = answersCopy [index]; answersCopy [index] = answersCopy [rand]; answersCopy [rand] = swapTemp1 } / / place the correct answer in the location of correctAnswerTargetLocation for (let I = 0; I < ANSWER_COUNT; I + = 1) {answers [I] = answersCopy [I];} const swapTemp2 = answers [0]; answers [0] = answers [correctAnswerTargetLocation]; answers [correctAnswerTargetLocation] = swapTemp2; return answers } exports.handler = function (event, context, callback) {try {let b = new InquiryBot (event); / / 0: debug 1: online b.botMonitor.setEnvironmentInfo (privateKey, 0); b.run () .then (function (result) {callback (null, result);}) .catch (callback);} catch (e) {callback (e);}}

At this point, the question and answer skills have been developed. Developers can test their skills on the simulation test page of the skills open platform.

On how to use nodejs BOT SDK to develop question and answer skills template is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report