How to Call AWS Lambda Functions From Amazon Alexa (Part 2)

DZone 's Guide to

How to Call AWS Lambda Functions From Amazon Alexa (Part 2)

Learn how to build the intent model for a Lambda function skill and the UI interaction. and use Backand to pull in a list of lambda functions and implement a vocal UI.

· IoT Zone ·
Free Resource

In Part 1 of this series, we walked through creating a custom Alexa skill that we’ll use to drive Lambda function calls. We also covered the AWS Lambda code that drives this skill, taking a brief look at the Alexa SDK, as it is used in one of the Alexa skill blueprints.

In this post, we’ll cover building the intent model for our Lambda function skill and the UI interaction. Then, we’ll use Backand to pull in a list of lambda functions and implement a vocal UI that can invoke these functions as desired by the user.

Creating Custom Intents

Amazon Alexa is driven based on an intent model. These intents are invoked using specific phrases (which you configure) and then handled with a handler function in the controlling AWS Lambda function for the Alexa skill. To begin creating your own intent, you’ll need to start on the configuration screen for the custom Alexa skill you are building:

From this screen, you can use the provided text box to build out your intent model using the JSON intent schema but this process can be fragile and, surprisingly, limited in some facets (dialogs between Alexa and the user, for example, can be challenging to construct in this schema). As an alternative, Amazon offers the Skill Builder tool:

The Skill Builder gives you an easy-to-use GUI on top of the Intent JSON (which is now accessible from the Code Editor tab), which makes building intents — and complex intent interactions — more manageable. Simply click on the Add button next to Intents and you’ll be able to create your own custom intents:

From here, you can name your intent, then either build a custom intent or repurpose a template that provides common functionality, such as choosing book names or providing details on an actor.

Obtaining a List of Lambda Functions

Using the above, we can now create custom intents that are handled by our AWS Lambda handler function. Let’s start by creating an Alexa intent that can fetch a list of functions from a Backand application using the Backand SDK. To begin, we’ll write a new intent in the skill builder, ListFunctions:

This function accepts a simple command — “list lambda functions” — and variations thereof and is intended to return a human-listenable list of Lambda functions from a Backand application. As such, the next step in our process is obtaining the list of available functions from Backand using the Backand Node.js SDK. Start by installing the SDK into your Lambda function’s package.json file as follows:

$ npm i -S @backand/nodejs-sdk

This will make fetching and calling functions easier. Once this is done, we need to import and configure the Backand SDK in the Lambda function’s code. To do so, add these lines near the top of your index.js file in your action:

const backand = require('@backand/nodejs-sdk');
     appName: 'BACKAND_APP_NAME',
     anonymousToken: 'BACKAND_ANONYMOUS_TOKEN'

This configures the Backand SDK to communicate with your Backand application — simply replace BACKAND_APP_NAME  and BACKAND_ANONYMOUS_TOKEN with the appropriate values obtained from your Backand application’s dashboard.

Now that we’ve configured the SDK, we’ll add a new handler for the intent we created — ListFunctions:

  'ListFunctions': function (event) {
    var context = this;
        method: 'GET',
        url: '1/action/config',
        params: {}
        fn_count = data.data.data.length;
        fn_data = data.data.data;
        var function_descriptors = [];
        for(var i = 0; i < fn_count; i++) {
          function_descriptors.push("Function "+(i+1) + ", " + fn_data[i].name + ". ");
          context.emit(':tell','There was an error afoot.')

This handler calls the Backand endpoint 1/action/config, which provides a list of the available actions in your Backand application and supporting data. We simply take that list of functions, prepend a handy identifier (more on this in the next section), and then use context.emit with a :tell command to have Alexa provide the list of functions to the user.

Creating a Vocal UI for Lambda

You’ll notice that the code for our handler was doing some decoration of the data before returning it to the user. As you work, it is important to keep in mind that the final results output need to be spoken to a user, and as such many of the return values will be more verbose than they would be if they were in a traditional application. You’ll need to make some compromises to accommodate Alexa’s speech patterns, and correct for any ambiguity in pronunciation.

A Quick Note on Language Processing

This also poses problems when designing vocal interactions, such as when building a skill that can execute arbitrary functions with arbitrary names. To summarize, Alexa has powerful voice capabilities, but can’t quite get to the level of precision needed to accommodate arbitrary, programming-styled function names. Take, for example, a Lambda function entitled QARestart5. Alexa faces several problems when attempting to parse this name:

  • QA can be interpreted as two separate abbreviations (i.e. Q. A.), or as actual words (i.e. “Queue hay”)
  • The number 5 can be presented as either the text “five” or as the Arabic numeral “5”
  • Input received from Alexa will try to treat each section of the compound word as a word itself

What this all means is that arbitrary function execution by name — while technically possible — is going to present a challenge. Instead, the above code settled on a different pattern. We assign a unique ID to each function — in this case, just an incrementing integer — and then use that as the discriminator to control invocation of the correct Lambda function.

This approach works for any combination of words that can be easily understood by Alexa. Another example would be combining a color and a city to give each function a random name that has semantic meaning decipherable by Amazon Alexa, such as “Blue Chicago” or “Grey Concord”. Simply choose a domain with sufficient variety to cover your list, develop a repeatable way to generate these descriptors, and you are set to go.

Calling a Function by ID

Now that we have the skeleton in place, we simply need to create a new intent —  RunFunction — that can invoke any of our arbitrary Lambda functions. To do so, start by creating a new intent in the Amazon Skill Builder, with a slot for Function Number:

The above command creates intent RunFunction, with a slot named number. This slot is given a type of  AMAZON.NUMBER, and will be turned into an integer representation of the function number spoken by the user. At this point, we simply need to add our new handler:

  'RunFunction': function (event) {
      var context = this;
      var number = context.event.request.intent.slots.number.value;
          method: 'GET',
          url: '1/action/config',
          params: {}
          fn_data = data.data.data;
          var function_id = number-1; // one-based instead of zero based
          var functionName = fn_data[function_id].name;
          backand.fn.get(functionName, {}).then(function{response}(
            // Assuming output is in variable "message"
            context.emit(':tell','There was an error afoot.')

The above function duplicates some code in the ListFunctions handler and is due for a refactor, but it should demonstrate the process. We fetch our list of functions from Backand again and, now that we have the list, we simply pick the entry corresponding to the function ID requested by the user. We do some modification of the input data to convert from a one-based system to a zero-based, but aside from that we simply take the number provided to us by the user and use Backand to execute that function.

You can expand this to include setting any parameter values, as well — simply fetch the list of parameters from your function and design an Alexa dialog for populating those parameters with the correct values. Be careful of working with programming data through this interface, though, as Alexa’s voice recognition — while excellent — still has a long way to go. Once you’ve finalized the interaction, you simply upload the code to your AWS Lambda function handling your Alexa skill, and you’re ready to go!

Expanding Functionality

Building an Alexa skill to drive your application’s Lambda functions can greatly increase your DevOps velocity. Using this technique, you can easily spin up new servers for your application, run simple reports that can return audible feedback or do any kind of processing that makes sense for voice commands. Simply find a mechanism for classifying your functions with an Alexa-capable identifier, and you’re set to go. We’ve put up a variation of this code on GitHub. This uses the techniques here to implement a simple restaurant exploration interface but can be updated to work with the listing technique with only minor modifications.


With that, you’re ready to accelerate your DevOps by enabling voice management of your infrastructure. While in many ways a technical demo, this example can be easily expanded into a full suite of DevOps functionality, giving your engineers yet another way to accomplish their goals as they pertain to running, maintaining, and reporting on your key IT assets. 

alexa skills ,amazon alexa ,aws lambda ,iot ,tutorial

Published at DZone with permission of Matt Billock , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}