Skip to content
Advertisement

Adding session attributes in Python for Alexa skills

I have 3 slots (account, dollar_value, recipient_first) within my intent schema for an Alexa skill and I want to save whatever slots are provided by the speaker in the session Attributes.

I am using the following methods to set session attributes:

JavaScript

However, as you may guess, if I want to save more than one slot as data in sessionAttributes, the sessionAttributes is overwritten as in the following case:

JavaScript

The JSON response from my lambda function for a speech input in which two slots (dollar_value and recipient_first) were provided is as follows (my guess is that the create_dollar_value_attribute method in the second if statement is overwriting the first):

JavaScript

The correct response for sessionAttributes should be:

JavaScript

How do I create this response? Is there a better way to add values to sessionAttributes in the JSON response?

Advertisement

Answer

The easiest way to add sessionAttributes with Python in my opinion seems to be by using a dictionary. For example, if you want to store some of the slots for future in the session attributes:

JavaScript

Next, you can just pass it on to the build response method:

JavaScript

The implementation in this case:

JavaScript

This creates the sessionAttributes in the recommended way in the Lambda response JSON.

Also just adding a new sessionAttribute doesn’t overwrite the last one if it doesn’t exist. It will just create a new key-value pair.

Do note, that this may work well in the service simulator but may return a key attribute error when testing on an actual Amazon Echo. According to this post,

On Service Simulator, sessions starts with Session:{ … Attributes:{}, … } When sessions start on the Echo, Session does not have an Attributes key at all.

The way I worked around this was to just manually create it in the lambda handler whenever a new session is created:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement