Thank you for your visit. This page is only available in English at this time.

Build a Skill End-to-end Using an Alexa-hosted Skill

With an Alexa-hosted skill, you can get started quickly using Alexa-hosted AWS resources to power your skill. An Alexa-hosted skill works in conjunction with a code editor in the developer console to edit and deploy changes to your AWS Lambda code. You can also use the Alexa Skills Kit Command Line Interface (ASK CLI) to edit and deploy an Alexa-hosted skill.

You can use Alexa-hosted skills to build an engaging skill by going through our interactive 90-minute Cakewalk tutorial. The course is aimed at those who want a hands-on experience with the Alexa Skills Kit (ASK) and voice user interface (VUI).

Setup

What services are included?
With an Alexa-hosted skill, you can build, edit, and publish a skill without leaving the developer console. You get access to an AWS Lambda endpoint, an Amazon S3 bucket for media storage, and an Amazon S3-backed key-value table for managing session persistence. The code editor allows you to edit the backend code for your skill and deploy directly to AWS Lambda. When you create the skill, the service also sets up an AWS CodeCommit repository for managing your code, which you can access by using the ASK CLI to edit your skill.
How do I access Alexa-hosted skills?
In the developer console, you can create an Alexa-hosted skill from the Create Skill page. The bottom of the page shows options for hosting the backend resources for your skill. Select the Alexa-hosted option. When you create your skill, the voice model, AWS resources, and code editor are activated, and the developer console initiates a build process for the voice model.
What types of skills can I build as an Alexa-hosted skill?
You can build a custom skill as an Alexa-hosted skill. You cannot use an Alexa-hosted skill to build a skill with a pre-built model, for example a smart home skill.
Do I need an AWS account?
No. You can provision the resources needed to power your Alexa skill directly from the Alexa developer console without an AWS account. If you need to use other AWS services or if your usage exceeds the AWS Free Tier, you need to provision the additional resources in your own AWS account.
Are Alexa-hosted skills available in all locales? In which region are the resources and endpoints hosted?
Alexa-hosted skills are available across all locales. All resources are hosted in the US East (N. Virginia) region, which may cause latency issues in skills located far from the region.
Can I run NPM (Node.js) or pip (Python) install with Alexa-hosted skills?
We provision AWS CodeBuild as part of the skill in order to execute the build script. NPM or pip install executes as part of the build script. You do not need to run NPM install because you can put dependencies into package.json, and AWS CodeBuild runs NPM install when you click the Deploy button.
How does Alexa confirm the uptime of Alexa-hosted skills and their connection to AWS Lambda?
To help ensure that calls to AWS Lambda from the Alexa-hosted skill work properly, the hosted skills service periodically sends an availability check to your AWS Lambda function. The following example shows the user alexa-lambda-availability sending the availability check, which is in the form of a LaunchRequest. If your skill performs an action when it receives a LaunchRequest, make sure to filter out requests from the user alexa-lambda-availability to prevent the availability check from causing your skill to perform an action.
{
  "version": "1.0",
  "session": {
    "new": true,
    "sessionId": "alexa-lambda-availability",
    "application": {
      "applicationId": "YOUR_SKILL_ID"
    },
    "user": {
      "userId": "alexa-lambda-availability"
    }
  },
  "context": {
    "AudioPlayer": {
      "playerActivity": "IDLE"
    },
    "System": {
      "application": {
        "applicationId": "YOUR_SKILL_ID"
      },
      "user": {
        "userId": "alexa-lambda-availability"
      },
      "device": {
        "deviceId": "test-device",
        "supportedInterfaces": {
          "AudioPlayer": {}
        }
      },
      "apiEndpoint": "https://api.amazonalexa.com",
      "apiAccessToken": "{token}"
    }
  },
  "request": {
    "type": "LaunchRequest",
    "requestId": "amzn1.echo-api.request.alexa.lambda.availability",
    "locale": "en-US",
    "shouldLinkResultBeReturned": false
  }
}

Usage limits

What are the usage limits?
Usage is limited to the AWS Free Tier. The following limits apply to each account. AWS Lambda: 1 million free AWS Lambda requests and 3.2 million seconds of compute time per month. Amazon S3: 5 GB of Amazon S3 storage, 20,000 get requests, 2,000 put requests, and 15 GB of data transfer out per month. AWS CodeCommit: 50 GB-month of storage and 10,000 Git requests per month.
What happens once a skill hits the thresholds of the AWS Free Tier?
Once your usage passes the limit of the AWS Free Tier, you have 30 days to bring usage below the limit by moving at least one of your skills to a personal AWS account or other cloud services account.
Where can I view the usage of Amazon S3 storage by the Alexa-hosted skill?
In the developer console, on the code editor tab, the Media storage information shows usage of Amazon S3. Usage includes storage of, for example, data for session persistence.
How many Alexa-hosted skills can I have on my developer.amazon.com account?
Your developer.amazon.com account is limited to 75 Alexa-hosted skills. When there are 75 Alexa-hosted skills on your account, you must delete an Alexa-hosted skill from your account before you can create another Alexa-hosted skill. Consider hosting some of your skills in a personal AWS account or other cloud services account.

Migration

How do I migrate an Alexa-hosted skill to another service?
To migrate a skill so that it is no longer an Alexa-hosted skill, change the endpoint in the developer console and manually copy and paste your code to your new endpoint. You must also move any resources hosted in Amazon S3.
What if I have an existing skill and I want to use an Alexa-hosted skill instead?
You need to create a new Alexa-hosted skill, and then add your content to the Alexa-hosted skill. At this time, you cannot transition an existing skill into an Alexa-hosted skill.

Programming languages

What programming languages are supported by Alexa-hosted skills?
Alexa-hosted skills currently supports Node.js version 8.10 and Python version 3.7. When you create a skill from the Console or CLI, you will have the opportunity to select a runtime at skill creation. Once you choose a runtime for a specific skill, it cannot be changed.

Skill resources

Are my files shared with other accounts?
The service places your files and resources in an individual account, separate from the accounts of other users. The developer console provisions and manages your individual account and the resources inside the account.
Are media files and tabular data encrypted when using an Alexa-hosted skill?
Yes. Alexa-hosted skills use Amazon S3 for media files and tabular data, and use the encryption methods supported by AWS.
How do I add a library or a new dependency to an Alexa-hosted skill?
You can add a dependency or library to the package.json file within the AWS Lambda package for the skill. Dependencies are fetched and built when you click the Deploy button.

Logs

How do I access my AWS Lambda logs via Amazon CloudWatch?
Alexa-hosted skills provide you with a limited view of the AWS console so that you can access information critical to developing your skill. To access the Amazon Cloudwatch logs for your skill, in the lower left corner of the code editor click the Logs: Amazon CloudWatch link, which opens a limited view of the AWS console and provides access to the logs.

Dependencies

How do I install dependencies in my skill?
You can use Node.js to install dependencies in the package.json file. An example of the code is shown below:
"aws-sdk": "^2.326.0"

You can use Python to install dependencies. You add dependencies in the requirements.txt file. An example of the code is shown below:

boto3==1.9.216

Session persistence

How do I use session persistence in an Alexa-hosted skill?
You can use Node.js or Python to add persistence.

Use session persistence with Node.js

  1. In your package.json file, add the following npm dependency in the dependencies section:

     "ask-sdk-s3-persistence-adapter": "^2.0.0"
    
  2. In your index.js file, add the following:

     // 1. import ask persistence adapter
     const persistenceAdapter = require('ask-sdk-s3-persistence-adapter');
    
     // 2. add the persistence adapter to your skill builder
     exports.handler = Alexa.SkillBuilders.custom()
         .addRequestHandlers(
             LaunchRequestHandler,
     ...
             SesssionEndedRequestHandler
         )
         .addErrorHandlers(ErrorHandler)
         .withPersistenceAdapter(
             new persistenceAdapter.S3PersistenceAdapter({bucketName:process.env.S3_PERSISTENCE_BUCKET})
         )
         .lambda();
    
     // 3. sample handler to save attributes
     async handle(handlerInput){
    
         const attributesManager = handlerInput.attributesManager;
         let s3Attributes = {"counter":10};
         attributesManager.setPersistentAttributes(s3Attributes);
         await attributesManager.savePersistentAttributes();
    
         let speechOutput = `Hi there, Hello World! Your saved counter is ${s3Attributes.counter}`;
    
         return handlerInput.responseBuilder
             .speak(speechOutput)
             .getResponse();
     },
    
     // 4. sample handler to read attributes
     async handle(handlerInput){
    
         const attributesManager = handlerInput.attributesManager;
         const s3Attributes = await attributesManager.getPersistentAttributes() || {};
         console.log('s3Attributes is: ', s3Attributes);
    
         const counter = s3Attributes.hasOwnProperty('counter')? s3Attributes.counter : 0;
    
         let speechOutput = `Hi there, Hello World! Your counter is ${counter}`;
    
         return handlerInput.responseBuilder
             .speak(speechOutput)
             .getResponse();
     },
    
    

Use session persistence with Python

  1. In your requirements.txt file, add the following pip dependency in the dependencies section:
     ask-sdk-s3-persistence-adapter==1.0.0
     ask-sdk-core==1.11.0
     boto3==1.9.216
    
  2. In your lambda_function.py file, add the following:

    #1. import ask persistence adapter and other dependencies.
    import os
    import boto3
    
    from ask_sdk_s3.adapter import S3Adapter
    from ask_sdk_core.skill_builder import CustomSkillBuilder

    #2. initialize the persistence adapter to your custom skill builder
    s3_adapter = S3Adapter(bucket_name=os.environ.get('S3_PERSISTENCE_BUCKET'))

    #3. add the persistence adapter to your custom skill builder
    sb = CustomSkillBuilder(persistence_adapter=s3_adapter)

    sb.add_request_handler(LaunchRequestHandler())
    sb.add_request_handler(CancelOrStopIntentHandler())
    sb.add_request_handler(SessionEndedRequestHandler())
    .
    .
    .
    sb.add_exception_handler(CatchAllExceptionHandler())

    lambda_handler = sb.lambda_handler()


    #4. sample handler to save attributes
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        attr = handler_input.attributes_manager.persistent_attributes
        if not attr:
            attr['counter'] = 0
            attr['state'] = 'ENDED'

        handler_input.attributes_manager.session_attributes = attr

        handler_input.attributes_manager.save_persistent_attributes()
        speak_output = ("Welcome you can say Hello or Help. Your saved counter is {}. What would you like to say?".format(attr["counter"]))
        reprompt = "Say hello or help to start."
        return (
            handler_input.response_builder
                .speak(speak_output)
                .ask(reprompt)
                .response
        )

    # 5. sample handler to read attributes
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        session_attr = handler_input.attributes_manager.session_attributes
        session_attr['state'] = "STARTED"
        session_attr["counter"] += 1
        handler_input.attributes_manager.persistent_attributes = session_attr
        handler_input.attributes_manager.save_persistent_attributes()

        speak_output = ("Hi there, Hello World! Your saved counter is {}.".format(session_attr["counter"]))
        return (
            handler_input.response_builder
                .speak(speak_output)
                # .ask("add a reprompt if you want to keep the session open for the user to respond")
                .response
        )

    # 6. sample handler to delete attributes
    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        session_attr = handler_input.attributes_manager.session_attributes
        session_attr['state'] = "ENDED"

        speak_output = ("Goodbye. Your counter is {}".format(session_attr["counter"]))

        handler_input.attributes_manager.delete_persistent_attributes()
        return (
            handler_input.response_builder
                .speak(speak_output)
                .response
        )

Media files

Use media files with Node.js

You can upload media files, for example pictures and audio, to the Amazon S3 bucket provisioned for your Alexa-hosted skill. To upload, in the lower left corner of the code editor click the Media storage: Amazon S3 link, which opens a new browser tab directing you to Amazon S3 functionality in the AWS console. The bucket name and folder appear similar to amzn1-ask-skill-xxxxxxx-xxxx-buildsnapshotbucket-xxxxx/Media/.

To access a file on Amazon S3 from the index.js for your skill, you need to require util.js and then get the pre-signed URL using the utility function getS3PreSignedUrl().

The URL expires in 60 seconds, and you cannot override the expiration from the utility function.

Picture File Example

The following code example shows picture.jpg as the requested file.

const Util = require('util.js');
handle(handlerInput){
const pictureUrl = Util.getS3PreSignedUrl("Media/picture.jpg");
return handlerInput.responseBuilder
    .speak('hello world with picture')
    .withStandardCard('card title', 'card text', pictureUrl)
    .getResponse();
}

Audio File Example

The following code example shows audio.mp3 as the requested file.

const Util = require('util.js');
handle(handlerInput){
const audioUrl = Util.getS3PreSignedUrl("Media/audio.mp3").replace(/&/g,'&');
return handlerInput.responseBuilder
    .speak(`hello world with audio <audio src="${audioUrl}"/>`)
    .getResponse();
}

The following actions are available when you access the media files for your hosted skill on Amazon S3 by using the link in the lower left corner of the console's code editor:

  • GetObject
  • PutObject
  • DeleteObject
  • ListBucket
  • ListAllMyBuckets

If public read access is necessary for a file, you will need to use a pre-signed URL.

Use Media files with Python

Picture File Example The following code example shows image.jpg as the requested file.

from ask_sdk_model import ui
from utils import create_presigned_url

def handle(self, handler_input):
    # type: (HandlerInput) -> Response
    image_url = create_presigned_url("Media/image.png")
    return (
        handler_input.response_builder
            .speak("hello world with picture")
            .set_card(ui.StandardCard(title="Card Title", text="Hey this is a sample card", image=ui.Image(small_image_url=image_url, large_image_url=image_url)))
            .response
    )

Audio File Example The following code example shows audio.m4a as the requested file. You can also choose to enable the audio interface in the Build tab. For more information, see AudioPlayer Interface Reference. For additional information on PlayDirective, see Alexa Skills Kit SDK for Python.

from ask_sdk_model.interfaces.audioplayer import AudioItem, Stream, PlayDirective, PlayBehavior
from utils import create_presigned_url

def handle(self, handler_input):
    # type: (HandlerInput) -> Response
    audio_url = create_presigned_url("Media/audio.m4a")
    handler_input.response_builder
    .add_directive(PlayDirective(play_behavior=PlayBehavior.REPLACE_ALL,audio_item=AudioItem(stream=Stream(token="1234AAAABBBBCCCCCDDDDEEEEEFFFF", url=audio_url,offset_in_milliseconds=10,expected_previous_token=None))))
    return (
        handler_input.response_builder.response
    )

Endpoint and deployment

What happens if I change my endpoint?
An Alexa-hosted skill provisions an AWS Lambda endpoint and links your skill to the endpoint. If you change the hosted endpoint, your skill is no longer an Alexa-hosted skill and the consoles code editor will not deploy to the new endpoint. In the console, after you change the endpoint, the code tab provides an option to reconnect to a hosted endpoint.
How do I deploy my code to a development endpoint?
Once your Alexa-hosted skill is published, two stages of your skill appear in the console, one for the live stage and one for the development stage. In the development stage for your skill, you can use the code editor to edit, save and deploy code to the development version of your AWS Lambda endpoint. This action does not affect the live endpoint for your skill. You can then go to the Test tab and test your changes.
How do I promote development changes to the live endpoint?
If you change the voice model for your skill, you must submit your skill for re-certification. If you change only the code for your skill, you can promote code from development to live by clicking the Promote to live button in the code editor. This action replaces the live code for your published skill.
How do I make a quick fix to my live endpoint?
To fix live code for an Alexa-hosted skill, it is recommended that you first make changes in the development stage, test the changes, and then promote the changes to the live endpoint for your skill. If you want to make a quick fix to your live code and your development code has other changes that you do not want to promote, you can make your fix directly to the live endpoint. However, you will not be able to test your changes. Open the code editor for the live stage, edit your code, and then deploy changes directly to the live endpoint. This action directly affects your live skill.

Personal AWS resources

How do I set up an Alexa-hosted skill to use resources on a personal AWS account?
With the AWS Lambda execution role ARN, you can seamlessly use resources on a personal AWS account to expand the functionality of your Alexa-hosted skill. For example, you can connect the Alexa-hosted skill to an Amazon DynamoDB table.

Use Node.js to set up your Alexa-hosted skill to use resources on a personal AWS account

Take the following steps to use Node.js to set up your Alexa-hosted skill to use resources on a personal AWS account.

  1. In the Alexa developer console, open your Alexa-hosted skill,
  2. In the code editor, click the icon that has hover text AWS Lambda Role Execution ARN. Copy the ARN.
  3. Create a role that allows access to the resource that you want your Alexa-hosted skill to access, on your personal AWS account, in the Identity and Access Management (IAM) dashboard. If you have not done so already.
  4. In the IAM dashboard, click Roles, click the name of the role you want to edit, and then click the Trust relationships tab.
  5. Edit the trust relationship to include the sts:AssumeRole action.
  6. Specify the AWS Lambda Role Execution ARN from your Alexa-hosted skill, as shown in the following example.

     {
       "Version": "2012-10-17",
       "Statement": [
             ... Your existing trust relationships ...,
             {
               "Effect": "Allow",
               "Principal": {
                 "AWS": "<Replace with AWS Lambda Execution Role ARN from Alexa-hosted skill>"
               },
               "Action": "sts:AssumeRole"
             }
       ]
     }
    
  7. In the code for your Alexa-hosted skill, assume the role using the AWS Security Token Service (STS) API. For example, the following code requests temporary credentials of a role with AWS DynamoDB access, and scans the DynamoDB table.

     const ShowUserMessageHandler = {
         ... Your canHandle function for intent ...
    
         async handle(handlerInput) {
             // 1. Assume the AWS resource role using STS AssumeRole Action
             const STS = new AWS.STS({ apiVersion: '2011-06-15' });
             const credentials = await STS.assumeRole({
                 RoleArn: '<Your AWS resource role ARN>',
                 RoleSessionName: 'ExampleSkillRoleSession' // You can rename with any name
             }, (err, res) => {
                 if (err) {
                     console.log('AssumeRole FAILED: ', err);
                     throw new Error('Error while assuming role');
                 }
                 return res;
             }).promise();
    
             // 2. Make a new DynamoDB instance with the assumed role credentials
             //    and scan the DynamoDB table
             const dynamoDB = new AWS.DynamoDB({
                 apiVersion: '2012-08-10',
                 accessKeyId: credentials.Credentials.AccessKeyId,
                 secretAccessKey: credentials.Credentials.SecretAccessKey,
                 sessionToken: credentials.Credentials.SessionToken
             });
             const tableData = await dynamoDB.scan({ TableName: 'TestTable' }, (err, data) => {
                 if (err) {
                     console.log('Scan FAILED', err);
                     throw new Error('Error while scanning table');
                 }
                 return data;
             }).promise();
    
             // ... Use table data as required ...
         }
     };
    

Use Python to set up your Alexa-hosted skill to use resources on a personal AWS account In the code for your Alexa-hosted skill, assume the role using the AWS Security Token Service (STS) API. For example, the following code requests temporary credentials of a role with AWS DynamoDB access, and then it scans the DynamoDB table.


import boto3

def handle(self, handler_input):
    # type: (HandlerInput) -> Response

    # 1. Assume the AWS resource role using STS AssumeRole Action
    sts_client = boto3.client('sts')
    assumed_role_object=sts_client.assume_role(RoleArn="<Your AWS resource role ARN>", RoleSessionName="AssumeRoleSession1")
    credentials=assumed_role_object['Credentials']

    # 2. Make a new DynamoDB instance with the assumed role credentials
    dynamodb = boto3.resource('dynamodb',
                      aws_access_key_id=credentials['AccessKeyId'],
                      aws_secret_access_key=credentials['SecretAccessKey'],
                      aws_session_token=credentials['SessionToken'],
                      region_name='us-east-1')

    # 3. Perform DynamoDB operations on the table
    try:
        table = dynamodb.Table('TestTable')
        response = table.scan()
        # Use the response as required . .
    except ResourceNotExistsError:
        # Exception handling
        raise
    except Exception as e:
        # Exception handling
        raise e
    # continue . .
    return (
        handler_input.response_builder.response
    )

ASK CLI

How do I get started using the ASK CLI with an Alexa-hosted skill?
To create a new Alexa-hosted skill with the ASK CLI, use the ask create-hosted-skill command. This creates a new Alexa-hosted skill in the development stage for your Amazon developer account, but it does not clone the skill to your local computer by default. To clone an Alexa-hosted skill to your local computer, you can:
  • Use the --auto-clone true option with the ask create-hosted-skill command, which creates a new Alexa-hosted skill and clones it to your computer with one command.
  • Use the ask clone command to clone an Alexa-hosted skill that you have already created.
How does the repository for an Alexa-hosted skill work with the ASK CLI?
When you clone an Alexa-hosted skill, the ASK CLI creates a folder that contains the Git repository with the code for your skill, as well as the interaction model and skill manifest. The repository is configured with the following branches:
  • The dev branch, which corresponds to the current saved state shown in the developer console.
  • The master branch, which corresponds to what is deployed to the development-stage AWS Lambda endpoint.
  • The prod branch, which corresponds to what is deployed to the live AWS Lambda endpoint, if your skill is already live.
How do common commands work in the ASK CLI with an Alexa-hosted skill?
The following shows how activity in the Git repository corresponds to activity in the developer console:
  • Pushing to the dev branch is equivalent to, on the Code tab of the developer console, clicking Save.
  • Pushing to dev, then merging dev into master, then pushing to master is equivalent to, on the Code tab of the developer console, clicking Deploy.
  • Merging master into prod and then pushing to prod is equivalent to, on the Code tab of the developer console, clicking Promote. This only deploys a quick fix to the code for your live skill, and does not deploy updates to the interaction model, like changes to slots, intents, and utterances.

The following procedure shows how to use the ask deploy command, which runs commands on the dev and master branches to push the code on your local computer to the development-stage AWS Lambda endpoint for your skill.

To use the ASK CLI to deploy changes to your Alexa-hosted skill:

  1. Make changes on the dev branch:
    <Make changes>
    <Navigate to the root directory for the Git repository>
    git add <file names>
    git commit
  2. Run the ask deploy command, which merges the dev branch into master, then pushes your local dev branch to the remote dev branch, and your local master branch to the remote master branch.

After you have tested your changes, use the developer console to start the process of publishing your skill to the Alexa Skills Store. For more information, see Test and Submit Your Skill for Certification.

How do I use the ASK CLI to make a quick fix to my live AWS Lambda endpoint?
If your skill is already published and you need to release a quick fix to your production code, you can promote your changes to live in the developer console by clicking Promote to live, or you can merge the master branch to prod by doing the following:
git checkout prod
git merge master
git push

This affects all customers using your skill, and does not deploy updates to the interaction model like changes to slots, intents, or utterances. You should also merge your quick fix into the dev and master branches, to ensure that your changes are not lost. Quick fixes are otherwise overwritten when a skill that is in development goes live, for example when the skill passes certification, or when you promote changes to live. In these situations, the code in the master branch is deployed and the code on the prod branch is replaced by forced merge.

What if I run into issues with the ASK CLI credential helper?
If you have an older version of Git installed and you have configured an AWS CodeCommit credential helper, you might see an error such as unable to access or the requested URL returned error: 403. To fix this issue, update Git to version 2.9 or later.