Create A Custom Skill To Demonstrate Dialog Delegation In Alexa

Introduction

 
In this article of custom Alexa skills, I am going to demonstrate how to create a custom Alexa skill on Alexa Hosted node.js server. For that, I will be creating a custom Alexa skill named City Facts. With the help of this skill, I will show how to implement dialog delegation in an Alexa skill. With the help of this skill, Users can ask Alexa to fetch information about different cities.
 
Each time Alexa asks if the user wants to know a fact about different cities. The users can give response by saying for example “give me a fact about London”. Alexa will fetch facts about the City London and prompt a message giving information about that particular city. The backend code required for the Alexa skill to work will be stored in a lambda function inside the Amazon developer console.
 

Creating an Alexa Skill

 
To create a new skill, first we need to login into the Alexa developer console, we need to mention the unique skill name and select the default language according to our location.
 
 
After that, we can choose a model to add to our skill. To create a custom skill, we can select custom model.
 
 
We can also choose a method or a template to host the skill’s backend code inside a lambda function.
 
 
We can choose Alexa hosted node.js or python template. We can also mention our own endpoint or server to store backend resources for the required Alexa skills.
 
Next step is to choose a template to add to our skill, which we customize later according to our need and click on create skill button. Now as skill has been created, we need to make adjustments to skill’s frontend. Now I will be creating intents, slots and custom slot types to create skill’s frontend.
 
First, we need to mention the invocation name. Users say a skill's invocation name to begin an interaction with a particular custom skill.
 
 
Now we have to create intents
 
 
Here, I have added a new intent named factIntent along with some sample utterances such as give me a fact, tell me a fact.
 
A custom slot type named CityName is defined for this Alexa skill.
 
 
Different slot values are defined such as Paris, Toronto, Sydney, etc.
 
After creating a model for a particular skill, we can save and build the model by clicking on save model and build model button on the top.
 
Json code for above frontend is as follows:
  1. {  
  2.     "interactionModel": {  
  3.         "languageModel": {  
  4.             "invocationName""city detail",  
  5.             "intents": [  
  6.                 {  
  7.                     "name""AMAZON.NavigateHomeIntent",  
  8.                     "samples": []  
  9.                 },  
  10.                 {  
  11.                     "name""AMAZON.CancelIntent",  
  12.                     "samples": []  
  13.                 },  
  14.                 {  
  15.                     "name""AMAZON.HelpIntent",  
  16.                     "samples": []  
  17.                 },  
  18.                 {  
  19.                     "name""AMAZON.StopIntent",  
  20.                     "samples": []  
  21.                 },  
  22.                 {  
  23.                     "name""factIntent",  
  24.                     "slots": [  
  25.                         {  
  26.                             "name""city",  
  27.                             "type""cityName",  
  28.                             "samples": [  
  29.                                 "give me a fact about {city}",  
  30.                                 "tell me some facts about {city}",  
  31.                                 "{city}"  
  32.                             ]  
  33.                         }  
  34.                     ],  
  35.                     "samples": [  
  36.                         "give me a fact",  
  37.                         "get a fact",  
  38.                         "tell me about {city}",  
  39.                         "get me a fact for {city}",  
  40.                         "tell me a fact",  
  41.                         "tell me a fact about {city}"  
  42.                     ]  
  43.                 }  
  44.             ],  
  45.             "types": [  
  46.                 {  
  47.                     "name""cityName",  
  48.                     "values": [  
  49.                         {  
  50.                             "name": {  
  51.                                 "value""paris"  
  52.                             }  
  53.                         },  
  54.                         {  
  55.                             "name": {  
  56.                                 "value""toronto"  
  57.                             }  
  58.                         },  
  59.                         {  
  60.                             "name": {  
  61.                                 "value""sydney"  
  62.                             }  
  63.                         },  
  64.                         {  
  65.                             "name": {  
  66.                                 "value""london"  
  67.                             }  
  68.                         },  
  69.                         {  
  70.                             "name": {  
  71.                                 "value""new delhi",  
  72.                                 "synonyms": [  
  73.                                     "delhi"  
  74.                                 ]  
  75.                             }  
  76.                         }  
  77.                     ]  
  78.                 }  
  79.             ]  
  80.         },  
  81.         "dialog": {  
  82.             "intents": [  
  83.                 {  
  84.                     "name""factIntent",  
  85.                     "confirmationRequired"false,  
  86.                     "prompts": {},  
  87.                     "slots": [  
  88.                         {  
  89.                             "name""city",  
  90.                             "type""cityName",  
  91.                             "confirmationRequired"false,  
  92.                             "elicitationRequired"true,  
  93.                             "prompts": {  
  94.                                 "elicitation""Elicit.Slot.251925459829.983270759031"  
  95.                             }  
  96.                         }  
  97.                     ]  
  98.                 }  
  99.             ],  
  100.             "delegationStrategy""SKILL_RESPONSE"  
  101.         },  
  102.         "prompts": [  
  103.             {  
  104.                 "id""Elicit.Slot.1162780729786.1432530920282",  
  105.                 "variations": [  
  106.                     {  
  107.                         "type""PlainText",  
  108.                         "value""which city are you going to?"  
  109.                     },  
  110.                     {  
  111.                         "type""PlainText",  
  112.                         "value""Where are you going?"  
  113.                     }  
  114.                 ]  
  115.             },  
  116.             {  
  117.                 "id""Elicit.Slot.1162780729786.1143025724798",  
  118.                 "variations": [  
  119.                     {  
  120.                         "type""PlainText",  
  121.                         "value""where are you starting your trip?"  
  122.                     },  
  123.                     {  
  124.                         "type""PlainText",  
  125.                         "value""What city are you leaving from?"  
  126.                     }  
  127.                 ]  
  128.             },  
  129.             {  
  130.                 "id""Elicit.Slot.1162780729786.801508773141",  
  131.                 "variations": [  
  132.                     {  
  133.                         "type""PlainText",  
  134.                         "value""what date are you flying out?"  
  135.                     },  
  136.                     {  
  137.                         "type""PlainText",  
  138.                         "value""When will you start this trip?"  
  139.                     }  
  140.                 ]  
  141.             },  
  142.             {  
  143.                 "id""Elicit.Slot.251925459829.983270759031",  
  144.                 "variations": [  
  145.                     {  
  146.                         "type""PlainText",  
  147.                         "value": "which city do you want to know the fact about,    
  148.                                      you can say london or paris or new delhi?"  
  149.                     }  
  150.                 ]  
  151.             }  
  152.         ]  
  153.     }  
  154. }  

Creating the backend resource for the Alexa skill

 
To create backend code inside a lambda function, we can write code inside the index.js node.js file. The code for the custom Alexa skill is as follows:
  1. const Alexa = require('ask-sdk-core');  
  2.   
  3. const facts = {  
  4.   'london'"Big Ben is arguably London's most famous landmark. Surprisingly, it is actually meant to go by the name 'The Clock Tower', while Big Ben is the name of the bell.",  
  5.   'paris'"The Eiffel Tower was supposed to be a temporary installation, intended to stand for 20 years after being built for the 1889 World Fair.",  
  6.   'toronto'"Almost 25% of Canada's population lives within a 160 km radius of Toronto.",  
  7.   'sydney'"The Sydney Harbour Bridge is the widest long-span bridge and tallest steel arch bridge in the world, and the 5th longest spanning-arch bridge according to Guinness World Records.",  
  8.   'new delhi'"Delhi is the second most populous city in the world with 25 million inhabitants! Census, in 2015, recorded 18.2 million people living in the city."  
  9. }  
  10.   
  11. const LaunchRequestHandler = {  
  12.   canHandle(handlerInput) {  
  13.     return handlerInput.requestEnvelope.request.type === 'LaunchRequest';  
  14.   },  
  15.   async handle(handlerInput) {  
  16.   
  17.     const responseBuilder = handlerInput.responseBuilder;  
  18.   
  19.     let speechText = 'Say tell me a fact to see the dialog delegate in action.';  
  20.     let repromptText = 'Say tell me a fact to see the dialog delegate in action.';  
  21.   
  22.     return responseBuilder  
  23.       .speak(speechText)  
  24.       .reprompt(repromptText)  
  25.       .getResponse();  
  26.   },  
  27. };  
  28.   
  29. const InProgressfactIntentHandler = {  
  30.   canHandle(handlerInput) {  
  31.     const request = handlerInput.requestEnvelope.request;  
  32.     return request.type === 'IntentRequest' &&  
  33.       request.intent.name === 'factIntent' &&  
  34.       request.dialogState !== 'COMPLETED';  
  35.   },  
  36.   handle(handlerInput) {  
  37.     const currentIntent = handlerInput.requestEnvelope.request.intent;  
  38.     return handlerInput.responseBuilder  
  39.       .addDelegateDirective(currentIntent)  
  40.       .getResponse();  
  41.   },  
  42. };  
  43.   
  44. const factIntentHandler = {  
  45.   canHandle(handlerInput) {  
  46.     return handlerInput.requestEnvelope.request.type === 'IntentRequest'  
  47.       && handlerInput.requestEnvelope.request.intent.name === 'factIntent';  
  48.   },  
  49.   async handle(handlerInput) {  
  50.     const responseBuilder = handlerInput.responseBuilder;  
  51.     const city = slotValue(handlerInput.requestEnvelope.request.intent.slots.city);  
  52.   
  53.     let speechText = `Here's a fact about ${city} - ${facts[city]}`;  
  54.       
  55.     return responseBuilder  
  56.       .speak(speechText)  
  57.       .getResponse();  
  58.   },  
  59. };  
  60.   
  61. const HelpIntentHandler = {  
  62.   canHandle(handlerInput) {  
  63.     return handlerInput.requestEnvelope.request.type === 'IntentRequest'  
  64.       && handlerInput.requestEnvelope.request.intent.name === 'AMAZON.HelpIntent';  
  65.   },  
  66.   handle(handlerInput) {  
  67.     const speechText = 'You can say tell me a fact about london';  
  68.   
  69.     return handlerInput.responseBuilder  
  70.       .speak(speechText)  
  71.       .reprompt(speechText)  
  72.       .getResponse();  
  73.   },  
  74. };  
  75.   
  76. const CancelAndStopIntentHandler = {  
  77.   canHandle(handlerInput) {  
  78.     return handlerInput.requestEnvelope.request.type === 'IntentRequest'  
  79.       && (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.CancelIntent'  
  80.         || handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StopIntent');  
  81.   },  
  82.   handle(handlerInput) {  
  83.     const speechText = 'Goodbye!';  
  84.   
  85.     return handlerInput.responseBuilder  
  86.       .speak(speechText)  
  87.       .getResponse();  
  88.   },  
  89. };  
  90.   
  91. const SessionEndedRequestHandler = {  
  92.   canHandle(handlerInput) {  
  93.     return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';  
  94.   },  
  95.   handle(handlerInput) {  
  96.     console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);  
  97.   
  98.     return handlerInput.responseBuilder.getResponse();  
  99.   },  
  100. };  
  101.   
  102. const ErrorHandler = {  
  103.   canHandle() {  
  104.     return true;  
  105.   },  
  106.   handle(handlerInput, error) {  
  107.     console.log(`Error handled: ${error.message}`);  
  108.   
  109.     return handlerInput.responseBuilder  
  110.       .speak('Sorry, I can\'t understand the command. Please say again.')  
  111.       .reprompt('Sorry, I can\'t understand the command. Please say again.')  
  112.       .getResponse();  
  113.   },  
  114. };  
  115.   
  116. function slotValue(slot, useId){  
  117.   if(slot.value === undefined){  
  118.       return "undefined";  
  119.   }  
  120.   let value = slot.value;  
  121.   let resolution = (slot.resolutions && slot.resolutions.resolutionsPerAuthority && slot.resolutions.resolutionsPerAuthority.length > 0) ? slot.resolutions.resolutionsPerAuthority[0] : null;  
  122.   if(resolution && resolution.status.code === 'ER_SUCCESS_MATCH'){  
  123.       let resolutionValue = resolution.values[0].value;  
  124.       value = resolutionValue.id && useId ? resolutionValue.id : resolutionValue.name;  
  125.   }  
  126.   return value;  
  127. }  
  128.   
  129. const skillBuilder = Alexa.SkillBuilders.standard();  
  130.   
  131. exports.handler = skillBuilder  
  132.   .addRequestHandlers(  
  133.     LaunchRequestHandler,  
  134.     InProgressfactIntentHandler,  
  135.     factIntentHandler,  
  136.     HelpIntentHandler,  
  137.     CancelAndStopIntentHandler,  
  138.     SessionEndedRequestHandler  
  139.   )  
  140.   .addErrorHandlers(ErrorHandler)  
  141.   .lambda();  
  142.   
  143.     
To receive request from the user, request handlers are created for each intent to handle.
 
Inside each handlers, canHandle and handle functions are defined.
 
The canHandle() function is where you define what requests the handler responds to. The handle() function returns a response to the user. If your skill receives a request, the canHandle() function within each handler determines whether or not that handler can service the request.
 
In this case, the user wants to launch the skill, which is a LaunchRequest. Therefore, the canHandle() function within the LaunchRequestHandler will let the SDK know it can fulfill the request. In computer terms, the canHandle returns true to confirm it can do the work.
 
With the help of LaunchRequestHandler, Alexa greets the user and says “Say tell me a fact to see the dialog delegate in action”. It asks the user to say “tell me a fact”. The user can ask for details of any city by making utterances such as “tell me a fact about New Delhi”.
 
After that, FactIntentHandler is defined to handle each and every request of user to know a random city fact. This handler will enable Alexa to tell users a fact about any city the user as asked for and also asks user if he/she wants to know about anymore city.
 
Inside InProgressFactIntentHandler, if dialog state shows not completed that is the request is not completed, then the intent will delegate the current intent passin the control back to Alexa service to decide what the next step is.
 
When the dialog state is completed, then factIntentHndler handles the result.
 
Output
 
 
As we can see from the output above, to invoke a skill, user can just say the invocation name. Here city details is an invocation name to invoke this skill. Alexa then greets and asks user to say tell me a fact and then Alexa prompts facts about different cities user has asked for.
 

Summary

 
In this article, I created a custom Alexa skill. I also defined invocation name, intents and sample utterances. I demonstrated the method to select city slot from the interaction model and tell a fact about that particular city. Proper coding snippets along with output for backend of skill is also provided. 


Similar Articles