Skip to content Skip to sidebar Skip to footer

Failed to Write to lambda_function.py. Please Try Again.

Smart home speakers were a novel thought just a couple of years ago. Today, they've become a central office of many people'south homes and offices and their adoption is only expected to grow. Among the virtually pop of these devices are those controlled by Amazon Alexa. In this tutorial, you lot'll become an Alexa Python developer past deploying your ain Alexa skill, an application that users will interact with using voice commands to Amazon Alexa devices.

In this tutorial, you'll learn:

  • What the main components of an Alexa skill are
  • How to set upwards an Alexa skill and create Intents
  • What the ask_sdk_core Alexa Python packet is
  • How to use ask_sdk_core to create the business logic of your Alexa Python skill
  • How to build, deploy, and test your Alexa Python skill using the online developer console

Getting Started With Alexa Python Development

To follow this tutorial, you'll need to brand a free Alexa programmer account. On that page, y'all'll take the post-obit steps:

  1. Click the Become Started push.
  2. Click the Sign-Upwardly button on the subsequent page.
  3. Click Create your Amazon Account.
  4. Fill out the grade with the required details.
  5. Click Submit to complete the sign-up process.

Yous'll too need to be familiar with concepts such as lists and dictionaries in Python, as well as JavaScript Object Annotation (JSON). If you're new to JSON, and so check out Working With JSON Data in Python.

Let'south get started!

Agreement Alexa Skills

An Alexa Python developer must be familiar with a number of different Alexa skill components, but the two most of import components are the interface and the service:

  1. The skill interface processes the user'south spoken language inputs and maps information technology to an intent.
  2. The skill service contains all the concern logic that determines the response for a given user input and returns information technology as a JSON object.

The skill interface will exist the frontend of your Alexa skill. This is where you'll define the intents and the invocation phrases that volition perform a certain office. Substantially, this is the part of the skill that'south responsible for interacting with the users.

The skill service will exist the backend of your Alexa skill. When a specific intent is triggered by the user, information technology volition send that information as a request to the skill service. This will contain the business organization logic to be returned along with valuable data to the frontend, which volition finally be relayed dorsum to the user.

Setting Upwardly Your Environment

It's time to start building your first Alexa Python skill! Sign in to the Alexa developer panel and click on the Create Skill button to get started. On the side by side page, enter the Skill proper noun, which will be Joke Bot:

Creating a new Alexa Skill

This will be the invocation phrase of your skill. It'due south the phrase a user will speak to starting time using your Alexa skill. You can change this to something else later on if you lot'd like. Also, note that Alexa skills can interact in many languages, which you tin see from the Default Language dropdown carte. For now, just set it to English (US).

Side by side, yous'll need to choose a model to add to your skill. These models are like templates that have been pre-designed by the Amazon team to help y'all get started with Alexa Python evolution, based on some mutual utilise cases. For this tutorial, you should select the Custom model.

Finally, you demand to select a method to host the backend of your Alexa skill. This service volition incorporate the business concern logic of your awarding.

For at present, select Alexa-Hosted (Python) as the backend for your Alexa skill. This will automatically provide you with a hosted backend within the AWS free tier so yous don't accept to pay anything upfront or prepare a complicated backend correct now.

Finally, click the Create Skill push button to proceed. Yous might exist asked to fill up out a CAPTCHA here, then consummate that as well. After a minute or so, you lot should be redirected to the Build department of the programmer console.

Agreement the Alexa Skill Model

One time you've logged into the Alexa programmer console and selected or created a skill, you'll be greeted with the Build department. This section provides you with a lot of options and controls to set up the interaction model of the skill. The components of this interaction model allow you lot to ascertain how the users will collaborate with your skill. These properties tin can be accessed through the left-side panel, which looks something similar this:

Alexa Developer Console Walkthrough

Every bit an Alexa Python programmer, there are a few components of an Alexa skill interaction model that you'll need to know nigh. The start is the invocation. This is what users will say to brainstorm interacting with your Alexa skill. For instance, the user will say, "Joke Bot," to invoke the Alexa skill yous'll build in this tutorial. You can change this from the Invocation section at whatsoever fourth dimension.

Another component is the intent, which represents the core functionality of your application. Your app will have a set of intents that will represent what kinds of actions your skill can perform. To provide contextual data for a given intent, y'all'll use a slot, which is a variable in an utterance phrase.

Consider the following example. A sample utterance to invoke the weather intent could be, "Tell me virtually the weather." To make the skill more useful, y'all can set the intent to be, "Tell me about the weather in Chicago," where the word "Chicago" volition be passed equally a slot variable, which improves the user experience.

Lastly, there are slot types, which define how information in a slot is handled and recognized. For instance, the AMAZON.DATE slot blazon easily converts words that indicate a appointment—like "today, "tomorrow", and others—into a standard appointment format (such as "2019-07-05"). You can check out the official slot blazon reference page to learn more.

At this point, the Intents panel should be open. If it's not, then y'all can open up it past selecting Intents from the sidebar on the left. You'll notice that there are five intents already set up by default:

Alexa Developer Console Intents Panel

The Intents console includes a HelloWorldIntent and five Built-in Intents. The built-in intents are there to remind you to account for some common cases that are important to making a convenient bot. Here'due south a brief overview:

  1. AMAZON.CancelIntent lets the user cancel a transaction or task. Examples include, "Never mind," "Forget it," "Go out," and "Abolish," though in that location are others.
  2. AMAZON.HelpIntent provides aid virtually how to use the skill. This could exist used to return a sentence that serves equally a transmission for the user on how to collaborate with your skill.
  3. AMAZON.StopIntent allows the user to get out the skill.
  4. AMAZON.NavigateHomeIntent navigates the user to the device dwelling house screen (if a screen is being used) and ends the skill session.

By default, there are no sample utterances assigned to trigger these intents, so y'all'll take to add together those as well. Consider it part of your training equally an Alexa Python developer. Yous can learn more about these built-in intents in the official documentation.

Viewing a Sample Intent

Later in this tutorial, you'll learn how to make a new intent, but for now, it's a practiced idea to take a look at some existing intents that are part of every new skill you create. To outset, click the HelloWorldIntent to meet its backdrop:

Hello World Intent Properties

Y'all tin can see the sample utterances that a user tin speak to invoke this intent. When this intent is invoked, this information is sent to the backend service of your Alexa skill, which will then execute the required business logic and render a response.

Below this, you lot have the pick to fix the Dialog Delegation Strategy, which allows y'all to delegate a specific dialog that you ascertain to a item intent. While you won't embrace this in this tutorial, you can read more about it in the official documentation.

Side by side, you take the choice to define slots for some particular data that your intent is supposed to collect. For example, if you were to create an intent that tells the weather for a given day, then you'd take a Date slot here that would collect the appointment information and send it to your backend service.

Whenever you brand changes to an intent, you lot need to click the Save Model button to save it. And so, y'all tin can click the Build Model button to go ahead and examination your Alexa Python skill.

It'south helpful to know that the interaction model of a skill can be completely represented in a JSON format. To run into the current construction of your Alexa skill, click the JSON Editor option from the left side console of the console:

Alexa Developer Console JSON Editor

If you make a modify directly using the JSON editor, then the changes are also reflected in the developer console UI. To test this behavior, add together a new intent and click Salvage Model.

Once y'all've fabricated all the necessary changes to the interaction model of your skill, yous can open the Test section of the programmer console to test out your skill. Testing is an of import role of condign an Alexa Python developer, so be sure not to skip this pace! Click the Test button from the superlative navigation bar on the developer panel. By default, testing volition be disabled. From the drop-downward carte du jour, select Evolution to start testing:

Alexa Developer Console Test Section

Hither, you take a number of ways that you can test out your Alexa Python skill. Allow's practice a quick test and so that y'all can go an idea of how your Alexa skill will respond to an utterance.

Select the Alexa Simulator option from the left side console, then enter the phrase, "Hey Alexa, open Joke Bot." You tin do this either by typing information technology in the input box or past using the Mic pick. Later on a couple of seconds, a response volition be returned dorsum to y'all:

Testing Alexa Simulator

In addition to the voice response, yous tin also see the JSON Input that was sent to the backend service of your Alexa skill, equally well equally the JSON Output that was received back to the panel:

Alexa Skill Test JSON Input/Output

Here'due south what's happened so far:

  • The JSON input object was constructed from input data that the user entered through voice or text.
  • The Alexa simulator packaged up the input along with other relevant metadata and sent it to the backend service. Yous can see this in the JSON Input box.
  • The backend service received the input JSON object and parsed it to check the blazon of the request. And then, it passed the JSON to the relevant intent handler part.
  • The intent handler function processed the input and gathered the required response, which is sent dorsum as a JSON response to the Alexa simulator. You tin see this in the JSON Output box.
  • The Alexa simulator parsed this JSON and read the speech communication response back to you.

Now that you have an overview of the unlike components of an Alexa skill and how information flows from one part to the other, it'southward time to start building your Joke Bot! In the adjacent section, you'll put your Alexa Python developer skills to the test by creating a new intent.

Creating New Intents

Let'due south start past creating the JokeIntent, which will return a random joke from a list to the user. Open the Build section of your Alexa developer console. Then, click the Add push button next to the Intents option from the left side panel:

Add new Intent

With the Create custom intent option selected, fix the name to JokeIntent and then click the Create custom intent button:

Create new Intent

Adjacent, you need to add together sample utterances that the user will speak to invoke this intent. These can be phrases similar "Tell me a joke" or "I want to hear a joke." Type in a phrase and click the plus sign (+) to add it as a sample utterance. Here's what that should wait like:

Add sample utterances for Intent

Yous tin add more than sample utterances, but for now, these will do just fine. Lastly, click the Salve Model button in the top-left corner of the window to save these changes.

Recollect, you'll demand to build your model before you can examination it out. Click the Build Model button to re-build the interaction model of your Alexa Python skill. You lot'll see a progress notification on the lesser-correct of your browser window. Once the build process is successful, you should run into another pop-up notification indicating the status of the build procedure.

You tin can check to see if the JokeIntent is successfully triggered or non. Click the Evaluate Model push in the superlative-right corner of the programmer console. A small window volition popular in from the side allowing you to bank check what intent will be triggered by a given input utterance. Type in any of the sample utterances to make certain that the JokeIntent is being invoked successfully.

Evaluate Interaction Model

To get rid of the evaluate pop-upwardly window, click the Evaluate Model button again.

Now that you've successfully created an intent, information technology'due south time to write the Python code that volition handle this intent and return dorsum a joke as a response.

Building the Skill Backend

At present that yous have an intent created that can exist triggered by the user, you need to add together functionality in the skill backend to handle this intent and return useful information. Open the Code section of the Alexa programmer console to get started.

When y'all open the Code section of the programmer panel, yous tin see an online code editor with some files already ready for you to get started. In particular, you'll see the following three files in the lambda sub-directory:

  1. lambda_function.py: This is the master entry point of the backend service. All the asking data from the Alexa intent is received here and is supposed to be returned from this file only.
  2. requirements.txt: This file contains the list of Python packages that are beingness used in this project. This is especially useful if y'all're choosing to set up your own backend service instead of using what's provided past Amazon. To acquire more about requirements files, cheque out Using Requirements Files.
  3. utils.py: This file contains some utility functions required for the lambda role to interact with the Amazon S3 service. Information technology contains some sample lawmaking on how to fetch data from an Amazon S3 bucket, which you might discover useful later on. Right now, this file is not being used in lambda_function.py.

For now, y'all'll just be making changes in lambda_function.py, then let'south take a closer look at the structure of the file:

                                                              vii                import                logging                                  8                import                ask_sdk_core.utils                as                ask_utils                                  9                10                from                ask_sdk_core.skill_builder                import                SkillBuilder                xi                from                ask_sdk_core.dispatch_components                import                AbstractRequestHandler                12                from                ask_sdk_core.dispatch_components                import                AbstractExceptionHandler                13                from                ask_sdk_core.handler_input                import                HandlerInput                14                15                from                ask_sdk_model                import                Response                16                17                logger                =                logging                .                getLogger                (                __name__                )                18                logger                .                setLevel                (                logging                .                INFO                )                19                twenty                21                class                LaunchRequestHandler                (                AbstractRequestHandler                ):                22                """Handler for Skill Launch."""                23                def                can_handle                (                self                ,                handler_input                ):                24                # type: (HandlerInput) -> bool                25                26                return                ask_utils                .                is_request_type                (                "LaunchRequest"                )(                handler_input                )                27                28                def                handle                (                self                ,                handler_input                ):                29                # type: (HandlerInput) -> Response                thirty                speak_output                =                "Welcome, you lot can say Hello or Help. "                \                31                "Which would y'all similar to try?"                32                33                render                (                34                handler_input                .                response_builder                35                .                speak                (                speak_output                )                36                .                ask                (                speak_output                )                37                .                response                38                )                39                ...                          

Outset, yous import the necessary utilities that were provided in the ask_sdk_core Alexa Python packet. Then, at that place are iii main tasks you lot demand to perform in lambda_function.py to handle a asking from an intent received from the front end-end of the Alexa skill:

  1. Create an intent handler class, which inherits from the AbstractRequestHandler course, with functions can_handle() and handle(). In that location are already a couple of handler classes defined in lambda_function.py, such as LaunchRequestHandler, HelpIntentHandler, and so on. These handle the fundamental intents of an Alexa skill. An important point to note here is that you demand to create a new intent handler form for each of the intents you define.
  2. Create a SkillBuilder object, which acts as the entry bespeak for your Alexa Python skill. This routes all the incoming request and response payloads to the intent handlers that you define.
  3. Pass the intent handler course as an statement to .add_request_handler() so that they're called in guild whenever a new request is received. The SkillBuilder is a singleton, so only one instance of it is needed to handle the routing of all incoming requests.

This is a good time for you to go through lambda_function.py. Y'all'll discover that the same pattern is followed over and over over again to handle unlike intents that can be triggered past your Alexa Python skill.

Now that you lot have a broad overview of all the different things y'all demand to do to handle an intent in your backend, it's time to write the lawmaking that will handle the JokeIntent that you built in the previous department.

Creating the JokeIntent Handler

Since the important utilities from the ask_sdk_core Alexa Python package take already been imported, you don't need to import them again. If you desire to acquire more about these in-depth, then y'all tin check out the official documentation.

Adjacent, you'll create a new intent handler that will handle the request received from the JokeIntent. In the code snippet below, the intent handler volition just return with a sample phrase. This indicates that the response to the JokeIntent was received from the backend. Add the following code to lambda_function.py above the course definition of LaunchRequestHandler():

                                            20                class                JokeIntentHandler                (                AbstractRequestHandler                ):                21                def                can_handle                (                cocky                ,                handler_input                ):                22                return                ask_utils                .                is_intent_name                (                "JokeIntent"                )(                handler_input                )                23                24                def                handle                (                cocky                ,                handler_input                ):                25                speak_output                =                "Hither'southward a sample joke for yous."                26                27                return                (                28                handler_input                .                response_builder                29                .                speak                (                speak_output                )                thirty                .                ask                (                speak_output                )                31                .                response                32                )                          

Allow'southward accept a wait at what each section does. In line twenty you lot create a new intent handler class for the JokeIntent, which is a kid class of the AbstractRequestHandler class. When yous create an intent in the frontend, you need to create an intent handler class in the backend that can handle requests from Alexa. The code you write for this needs to do two things:

  1. JokeIntentHandler.can_handle() recognizes each incoming asking that Alexa sends.
  2. JokeIntentHandler.handle() returns an appropriate response.

In line 21 you define .can_handle() . It takes in handler_input equally a parameter, which is an object of type dict() that contains all the input request data. Then, information technology uses ask_utils.is_intent_name() or ask_utils.is_request_type() to cheque whether the JSON input it received tin be handled by this intent handler part or not.

You use .is_intent_name() and pass in the name of the intent. This returns a predicate, which is a office object that returns Truthful if the given handler_input originates from the indicated intent. If this is true, and then the SkillBuilder object will phone call JokeIntentHandler.handle().

This argument subsequently calls .handle() , which you define in line 24. This method receives the input request forth with any other important information that might be needed. It contains the business logic that'due south required to successfully handle a item intent. In the example of the JokeIntent, this method is required to send a response containing a joke back to the Alexa frontend.

The speak_ouput variable contains the judgement which will be spoken back to the user past the Alexa skill frontend. speak(speak_output) indicates what the Alexa frontend will play to the user as speech. ask("Question to ask...") tin can be used to ask a follow-upwards question. In this method, an object of class response_builder returns the response back to the Alexa skill.

Notice that the value of speak_output is set to a fixed response right now. You'll change this afterward to return a random joke from a listing of jokes.

Here'south what your code looks like in an editor:

Creating new Intent Handler

Once you've created an intent handler class, you need to pass information technology every bit an argument to SkillBuilder.add_request_handler. Scroll to the bottom of lambda_function.py and add the post-obit line:

                                            sb                .                add_request_handler                (                JokeIntentHandler                ())                          

An important matter to note here is that the placement of this line is important, as the code is processed from meridian to bottom. So, make sure that the call for your custom intent handler is in a higher place the call for the InstantReflectHandler() form. This is how it should look:

                                            171                sb                =                SkillBuilder                ()                172                173                sb                .                add_request_handler                (                LaunchRequestHandler                ())                174                                  sb                  .                  add_request_handler                  (                  JokeIntentHandler                  ())                                175                sb                .                add_request_handler                (                HelloWorldIntentHandler                ())                176                sb                .                add_request_handler                (                HelpIntentHandler                ())                177                sb                .                add_request_handler                (                CancelOrStopIntentHandler                ())                178                sb                .                add_request_handler                (                SessionEndedRequestHandler                ())                179                180                # Brand certain IntentReflectorHandler is final and so it                181                # Doesn't override your custom intent handlers                182                sb                .                add_request_handler                (                IntentReflectorHandler                ())                183                184                sb                .                add_exception_handler                (                CatchAllExceptionHandler                ())                185                186                ...                          

Alright, it's time to test your lawmaking! Click the Deploy push to save the changes and deploy the backend service. Y'all'll be checking whether it's going to work every bit expected from the Alexa skill frontend.

Once the Deploy process is successful, head back to the Test section of the developer console and invoke the JokeIntent. Think, enter the utterance phrase to invoke your Alexa Python skill, then input a phrase to execute an intent:

Testing the Joke Intent

If you get a response similar to the one in the paradigm above, then it means you've successfully created an intent handler for the JokeIntent in your skill's backend service. Congratulations! Now, all that'southward left to do is to return a random joke from a listing dorsum to the skill frontend.

Adding Jokes

Open the Code department of the programmer console. And so, add together the jokes variable in lambda_function.py:

                                            15                from                ask_sdk_model                import                Response                sixteen                17                logger                =                logging                .                getLogger                (                __name__                )                xviii                logger                .                setLevel                (                logging                .                INFO                )                xix                20                                  jokes                  =                  [                                21                                  "Did you hear nigh the semi-colon that broke the law? He was given two consecutive sentences."                  ,                                22                                  "I ate a clock yesterday, information technology was very time-consuming."                  ,                                23                                  "I've merely written a song about tortillas; actually, it's more than of a rap."                  ,                                24                                  "I woke up this morning and forgot which side the sun rises from, then it dawned on me."                  ,                                25                                  "I recently decided to sell my vacuum cleaner as all it was doing was gathering dust."                  ,                                26                                  "If yous shouldn't eat at dark, why exercise they put a lite in the refrigerator?"                  ,                                27                                  ]                                28                29                class                JokeIntentHandler                (                AbstractRequestHandler                ):                30                ...                          

Here, jokes is a variable of type listing containing some i-liner jokes. Make sure to add this outside of a part or course definition and then that it has global scope.

Next, yous'll add the functionality that .handle() needs to randomly pick one joke from the list of jokes and return it to the user. Modify the body of JokeIntentHandler.handle() with the post-obit lawmaking:

                                            29                class                JokeIntentHandler                (                AbstractRequestHandler                ):                30                def                can_handle                (                self                ,                handler_input                ):                31                return                ask_utils                .                is_intent_name                (                "JokeIntent"                )(                handler_input                )                32                33                def                handle                (                self                ,                handler_input                ):                34                speak_output                =                random                .                choice                (                jokes                )                35                                                36                return                (                37                handler_input                .                response_builder                38                .                speak                (                speak_output                )                39                .                inquire                (                speak_output                )                40                .                response                41                )                          

In the body of .handle(), you select a random joke from the list jokes using random.choice() and return information technology back as a response to the Alexa skill frontend.

Finally, import the random bundle by adding an import statement to the tiptop of lambda_function.py:

                                            fifteen                from                ask_sdk_model                import                Response                16                17                                  import                  random                                18                19                logger                =                logging                .                getLogger                (                __name__                )                20                logger                .                setLevel                (                logging                .                INFO                )                21                22                ...                          

This is how the editor should look at this point:

Updating the Joke Intent Handler

At that place's one final alter to make before testing. You need to permit Alexa to give an acquittance that the skill has been triggered. To practise this, look inside LaunchRequestHandler.handle() for the speak_output variable and set its value to the text in the highlighted line beneath:

                                            45                grade                LaunchRequestHandler                (                AbstractRequestHandler                ):                46                """Handler for Skill Launch."""                47                def                can_handle                (                self                ,                handler_input                ):                48                # type: (HandlerInput) -> bool                49                fifty                return                ask_utils                .                is_request_type                (                "LaunchRequest"                )(                handler_input                )                51                52                def                handle                (                self                ,                handler_input                ):                53                # type: (HandlerInput) -> Response                54                                  speak_output                  =                  "Hey there! I am a Joke Bot. You can ask me to tell yous a random Joke that might but brand your twenty-four hour period amend!"                                55                56                return                (                57                handler_input                .                response_builder                58                .                speak                (                speak_output                )                59                .                inquire                (                speak_output                )                sixty                .                response                61                )                62                ...                          

Your Joke Bot is fix for terminal testing! Click the Deploy button to save the changes and head back to the Test section of the developer console. This time, you should run into a new greeting message when your skill is beginning invoked. And so, when you inquire the bot to tell yous a joke, it should give you lot a different joke every time:

Final Testing of Python Alexa Skill

That'southward it! You've successfully created your first skill as an Alexa Python programmer!

Conclusion

Congratulations on taking your beginning steps into Alexa Python development! Yous've at present successfully congenital your very own Alexa Python skill. You at present know how to create a new skill, create intents, write Python code to handle those intents, and render valuable information dorsum to the user.

Level-upwards your skills past trying some of the post-obit:

  • Increment the list of jokes in the backend.
  • Create a new Intent named Trivia which will respond with a fun trivia fact.
  • Publish your skill to the Amazon Marketplace.

The possibilities are endless, so become ahead and dive right in! To acquire more than well-nigh Alexa Python evolution, check out the official docs. Yous can besides cheque out How to Make a Twitter Bot in Python With Tweepy and How to Make a Discord Bot in Python to learn more about how you can make bots for unlike platforms using Python.

petersentrompair.blogspot.com

Source: https://realpython.com/alexa-python-skill/

Post a Comment for "Failed to Write to lambda_function.py. Please Try Again."