Home >Technology peripherals >It Industry >How to Build Your First Amazon Alexa Skill

How to Build Your First Amazon Alexa Skill

William Shakespeare
William ShakespeareOriginal
2025-02-15 10:33:11238browse

How to Build Your First Amazon Alexa Skill

Key Points

  • Developers can use the Alexa Skill Kit (ASK) to create custom skills for Amazon Alexa. ASK is a collection of APIs and tools for handling speech recognition, text-to-speech encoding, and natural language processing.
  • To create a custom Alexa skill, you first need to set up an Amazon developer account. Once set up, you can access the Alexa Skills Kit and create custom skills, define their names and models.
  • Custom Alexa skills include call name (name used to activate the skill), intent (voice commands for skill understanding), and discourse (example sentences that trigger the intention).
  • After setting up a skill and defining its components, developers can test the skill in the Alexa Skills Kit developer console, modifying the code as needed to ensure it responds to voice commands correctly.
  • More advanced Alexa skills can be developed, such as skills that control smart home devices or pass parameters through intentions. Developers can also use Alexa Presentation Language (APL) to create visual and audio experiences for their skills.

Alexa natively supports many built-in skills such as adding items to your shopping list or requesting songs. However, developers can use the Alexa Skill Kit (ASK) to build new custom skills.

ASK is a collection of APIs and tools that handle most of the work related to the voice interface, including speech recognition, text-to-speech encoding, and natural language processing. ASK helps developers build skills quickly and easily.

In short, the only reason Alexa can understand user voice commands is that it defines skills. Each Alexa skill is software designed to understand voice commands. Additionally, each Alexa skill has its own defined logic that creates the appropriate response for voice commands. To give you some existing Alexa skills, they include:

  • Order pizza at Domino's Pizza
  • Call Uber
  • Tell you your horoscope

As mentioned above, we can use the Alexa Skill Kit to develop custom skills that meet our needs, a collection of APIs and tools designed for this purpose. ASK includes tools such as speech recognition, text-to-speech encoding and natural language processing. The toolkit should allow any developer to quickly start developing their own custom skills.

In this article, you will learn how to create a basic "get facts" Alexa skill. In short, we can ask Alexa to show us a random cat fact. The complete code to complete the task can be found on GitHub. Before we get started, let’s make sure we understand the Alexa skill terminology.

Master Alexa Skill Terminology

First, let's learn how users interact with custom skills. This is very important for understanding different concepts related to skills.

To activate a specific skill, the user must call Alexa and ask to turn on the skill. For example: "Alexa, open the cat facts". By doing this, we are calling the call name of the skill. Basically, the call name can be regarded as the name of the application.

Now that we have activated the correct skills, we can access the voice intent/commands that the skills understand. Since we want to keep it simple, we define a "get cat facts" intention. However, we need to provide example sentences to trigger the intent. An intention can be triggered by many example sentences, also called discourse. For example, the user might say "given a fact". Therefore, we define the following example sentences:

  • "Say a fact"
  • "Give a cat fact"
  • "Give a fact"

You can even combine the call name with the intent, as follows: "Alexa, ask the cat facts to give the facts".

Now that we know the difference between call name and intent, let's go ahead and create your first Alexa skill.

Create an Amazon developer account

First of all, we need an Amazon developer account. If you already have one, you can skip this section.

Registering an Amazon developer account is a three-step process. Amazon requires some personal information, accepts the terms of service and provides payment methods. The advantage of signing up for an Amazon developer account is that you have access to a large number of other Amazon services. After successfully completing the registration, you will see the Amazon Developer Control Panel.

Login to the control panel and click the "Developer Console" button in the upper right corner.

How to Build Your First Amazon Alexa Skill

Next, we want to open the Alexa Skills Kit.

How to Build Your First Amazon Alexa Skill

If you cannot open the Alexa Skills Kit, please use this link.

In the next section, we will create our actual skills.

Create our first custom Alexa skills

Okay, we're ready to create our first custom Alexa skill. Click the blue button "Create Skill" to open the menu for creating new skills.

How to Build Your First Amazon Alexa Skill

First, it prompts us to enter the name of the skill. As you already know, we want random cat facts, so we call the skill “custom cat facts” (we can’t use “cat facts” because this is a built-in skill for Alexa devices). Next, it prompts us to choose a model for your skills. We can choose some predefined models, or choose a custom model, which gives us complete flexibility. Since we don't want to deal with unwanted code, we select the "Custom" option.

*Note: If you choose a predefined skill, you will get a list of interaction models and example sentences (discourses). However, even custom skills are equipped with the most basic intentions such as canceling, helping, navigating to the homepage and stopping.

How to Build Your First Amazon Alexa Skill

Next, we need to choose a way to host our skills. Again, we don't want to overcomplicate things and select the "Alexa Hosting (Node.js)" option. This means we don't have to run the backend ourselves, which takes some effort to make it "Alexa compliant". This means you have to format the response according to Amazon Alexa standards so that the device can understand this. The Alexa hosting option will:

Hosting skills in your account until the AWS Free Tier limit and getting you started using the Node.js template. You will have access to AWS Lambda endpoints, 5 GB of media storage (15 GB of data transfer per month), and tables for session persistence.

How to Build Your First Amazon Alexa Skill

OK, now all the settings are in place, you can click the Create Skill button in the upper right corner of the screen. This button will generate actual skills in our Amazon developer account.

Modify your first Alexa skill

Now, if you navigate to the Alexa Developer Console, you will find that your skills are listed there. Click the Edit button to start modifying skills.

How to Build Your First Amazon Alexa Skill

Next, Amazon will display the Build tab of the "Cat Facts" skill. On the left you will find a list of intents defined for the skill. As mentioned earlier, by default, the Alexa Skills Kit generates a Cancel, Stop, Help, and Navigate to Home page intent. The first three are helpful for users who want to quit their skills or don't know how to use them. The last "Navigation to Home" is for complex skills that involve multiple steps only.

How to Build Your First Amazon Alexa Skill

Step 1: Verify the call name

First, let's verify that the call name of the skill is correct. The name should appear as "Custom Cat Facts".

If you change the name, make sure to click the "Save Model" button at the top of the page.

How to Build Your First Amazon Alexa Skill

Step 2: Change "HelloWorldIntent"

Second step, we want to modify the default intent "HelloWorldIntent".

Click on the intent and we will get a nice graphical interface that allows us to change the intent name or add sample discourse.

How to Build Your First Amazon Alexa Skill

I personally prefer using the JSON editor, which you can find in the menu on the left. When you open the JSON editor, you will see the following JSON object.

How to Build Your First Amazon Alexa Skill

The advantage of the JSON editor is that you can modify all intents at once. First, let's add a new intent called "GetFactIntent".

Next, we want to add some example discourses as shown in the picture below.

How to Build Your First Amazon Alexa Skill

After modifying, your JSON object should look like this. Currently, we do not want to define sample discourse for other intentions. Alexa Skills Kit links the Help sentence to "HelpIntent" by default.

Note: Don't forget to click the "Save Model" button and then click the "Build Model" button. Alexa basically builds the model and trains itself based on the model you define with the example discourse.

How to Build Your First Amazon Alexa Skill

Step 3: Test the "Custom Cat Facts" skill

Let's go to the Test tab in the horizontal menu. Now switch the "Skill Test Already" drop-down menu to "Development". This will allow us to test our skills.

Currently, let's try to activate the skills to see if everything is correct. We can activate the skill by calling the call name, as shown in the figure below.

How to Build Your First Amazon Alexa Skill

Step 4: Modify the code of GetFactIntent

Next, we'll dive into the code tab. When you click the Code tab, you will get an online editor with the default code.

First, we want to copy the code of HelloWorldIntentHandler and rename it to GetFactIntentHandler.

After

, we must specify which type of intent this handler can handle. Line 21 looks for an intent named GetFactIntent.

Now that we have found the intent, let's define a static response: "I'll say a fact!", we assign it to the speakOutput variable.

How to Build Your First Amazon Alexa Skill

Finally, we have to add the GetFactIntentHandler to the other request handlers. We can simply add it to the addRequestHandlers function. Don't forget to save and build the intention!

How to Build Your First Amazon Alexa Skill

Now that the skill has been saved and built, let's briefly verify the response. If we ask the skill to tell the facts, it should reply “I will tell a fact!”

How to Build Your First Amazon Alexa Skill

If everything is correct, you can move on to the next step.

Step 5: Query the API to retrieve cat facts

As the last step, we want to query a simple API that returns cat facts. To do this, I use the following API endpoint: https://www.php.cn/link/2c5baeed3fd870447056fc00bf792427.

This API endpoint returns the facts and the length of the facts.

<code>{
  "fact": "Smuggling a cat out of ancient Egypt was punishable by death. Phoenician traders eventually succeeded in smuggling felines, which they sold to rich people in Athens and other important cities.",
  "length": 192
}</code>

Since the https package is built in for Node.js, we can use it in our code to retrieve data from the API. This is how we do it:

How to Build Your First Amazon Alexa Skill

The actual code can be found here:

<code class="language-javascript">const https = require('https');

const httpGet = () => {
  return new Promise(((resolve, reject) => {
    var options = {
        host: 'catfact.ninja',
        port: 443,
        path: '/fact',
        method: 'GET',
    };

    const request = https.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';

      response.on('data', (chunk) => {
        returnData += chunk;
      });

      response.on('end', () => {
        resolve(JSON.parse(returnData));
      });

      response.on('error', (error) => {
        reject(error);
      });
    });
    request.end();
  }));
}</code>

Now that we have the helper method ready, we can add it to the GetFactIntentHandler. Note that since we want to use await for the request, we have to make the handle function an asynchronous function. In addition, we call the httpGet function to get the cat fact response and assign response.fact to the speakOutput variable. Next, the speakOutput variable is passed to the speak command, which is used by Alexa:

<code class="language-javascript">const GetFactIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'GetFactIntent';
    },
    async handle(handlerInput) {
        // const speakOutput = 'I will tell a fact!';
        const response = await httpGet();
        const speakOutput = response.fact;
        return handlerInput.responseBuilder
            .speak(speakOutput)
            //.reprompt('add a reprompt if you want to keep the session open for the user to respond')
            .getResponse();
    }
};</code>

How to Build Your First Amazon Alexa Skill

We are ready to change the code. Save the code again and click the Deploy button.

Step 6: Final Skill Test

As a final step, let's verify that the skill gets the random cat fact from the API. Again, let's go to the Tests tab.

Activate the skill by calling "Open Cat Facts". Next, you can ask for “tell the truth.” If all goes well, you should receive a fact in response.

How to Build Your First Amazon Alexa Skill

Success!

Step 7 (optional): Test on a real Alexa device

To test your custom skills on Alexa-enabled devices, you need to register your Alexa device under the same email address as your Amazon developer account.

More information can be found in the Alexa documentation:

To test with an Alexa-enabled device, such as Amazon Echo, register the device with the same email address you used to register a developer account on the Amazon Developer Portal. You can then call your skill using the wake word and your call name: "Alexa, open ."

If your device is using an account other than your developer account for setting up, reset the device and re-register with your developer account.

Understanding the basics

This is just the beginning of building skills with Alexa. More advanced examples are possible, such as passing parameters (options) using intent. Many other types of skills can also be developed, such as skills to control smart home devices.

If you want to learn more about Alexa Skill development, find the following resources:

  • End-to-end building skills—Amazon Alexa Documentation
  • Skill examples provided by Alexa Node.js project
  • Voice Design Guide

FAQs about Amazon Alexa Skill (FAQ)

How to create Alexa skills for my website?

Creating Alexa skills for your website involves multiple steps. First, you need to set up an Amazon developer account. Once you have an account, navigate to the Alexa Skills Kit Developer Console and click Create Skills. You need to give your skill a name and select a model to add to your skill. After that, you need to build an interactive model for your skills, including intentions, slots, and sample discourse. After building the interactive model, you can continue to test your skills in the developer console before publishing.

What are the key components of Alexa skills?

Alexa skills contain several key components. These include call names (the name the user uses to activate your skill), intent (represents an action that satisfies the user's request), slots (variables that act as placeholders for user input), and sample discourses (users may use to interact with your skill phrase). Each of these components plays a crucial role in how your skills work and interact with users.

How to test my Alexa skills?

Testing your Alexa skills is an important part of the development process. You can test your skills in the Alexa Skills Kit Developer Console. Simply navigate to the Tests tab in the console to start testing your skills. You can type or speak phrases to see how your skills respond, and you can also test multiple rounds of conversations to see how your skills handle the ongoing interactions.

How to post my Alexa skills?

After building and testing Alexa skills, you can submit it in the Alexa Skills Kit Developer Console for certification. Before submitting your skills, make sure you have completed all the necessary steps in the development process, including setting up the metadata of your skills and thoroughly testing your skills. After submitting the skill, it will go through the review process before it can be published.

What is Alexa Presentation Language (APL)?

Alexa Presentation Language (APL) is a language that allows developers to create visual and audio experiences for Alexa skills. With APL, you can design rich, interactive displays for devices with screens, and create audio responses for devices without screens. APL is a powerful tool to enhance the user experience of Alexa skills.

How to use APL in my Alexa skills?

To use APL in your Alexa skills, you need to include APL instructions in the skill's response. These instructions define the visual and audio components of the response. You can design your APL document using the APL authoring tool in the Alexa Skills Kit Developer Console, which provides a visual interface for creating and previewing designs.

What is the Alexa Web API for gaming?

The Alexa Web API for gaming is a set of web technologies that allow developers to create visually rich and interactive gaming experiences for Alexa devices with screens. Using the Alexa Web API for gaming, you can use standard web technologies such as HTML, CSS, and JavaScript to build your gaming experience.

How to use the Alexa Web API for gaming in my Alexa skills?

To use the Alexa Web API for gaming in your Alexa skills, you need to include the Alexa Web API interface for gaming in your skills list. You can then start a web application session using the Alexa.Presentation.HTML.Start directive and you can use the Alexa.Presentation.HTML.HandleMessage directive to process messages from your web application.

What is Alexa Skills Kit (ASK)?

Alexa Skills Kit (ASK) is a collection of self-service APIs, tools, documentation, and code examples that make it easier for you to build skills for Alexa. With ASK, you can take advantage of Amazon’s knowledge and groundbreaking work in the field of voice design.

How to use the Alexa Skills Kit (ASK) to build my Alexa skills?

You can build your Alexa skills using the Alexa Skills Kit (ASK) by leveraging its various features and tools. ASK provides a range of resources including the ASK SDK, the ASK CLI, the ASK developer console, and the ASK documentation. These resources provide a comprehensive set of tools to build, test and publish your Alexa skills.

The above is the detailed content of How to Build Your First Amazon Alexa Skill. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn