Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Amazon Lex

Download as pdf or txt
Download as pdf or txt
You are on page 1of 379
At a glance
Powered by AI
Amazon Lex is an AWS service for building conversational interfaces into any application using voice and text. It allows developers to define intelligent agents that understand natural language and converse with users.

Amazon Lex is an AWS service that allows developers to build conversational interfaces into any application using voice and text. It allows developers to define intelligent agents that understand natural language and converse with users.

The main components of Amazon Lex include intents, slots, built-in slot types, Lambda functions, and conversation models.

Amazon Lex

Developer Guide
Amazon Lex Developer Guide

Amazon Lex: Developer Guide


Copyright © 2018 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner
that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not
owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by
Amazon.
Amazon Lex Developer Guide

Table of Contents
What Is Amazon Lex? ......................................................................................................................... 1
Are You a First-time User of Amazon Lex? ..................................................................................... 2
How It Works .................................................................................................................................... 3
Programming Model ................................................................................................................... 4
Model Building API Operations ............................................................................................ 5
Runtime API Operations ...................................................................................................... 5
Lambda Functions As Code Hooks ........................................................................................ 6
Service Permissions .................................................................................................................... 8
Creating Resource-Based Policies for AWS Lambda ................................................................. 8
Deleting Service-Linked Roles .............................................................................................. 8
Managing Messages .................................................................................................................... 9
Types of Messages ............................................................................................................. 9
Contexts for Configuring Messages ..................................................................................... 10
Supported Message Formats .............................................................................................. 14
Message Groups ............................................................................................................... 14
Response Cards ................................................................................................................ 15
Managing Conversation Context ................................................................................................. 19
Setting Session Attributes ................................................................................................. 19
Setting Request Attributes ................................................................................................ 20
Setting the Session Timeout .............................................................................................. 22
Sharing Information Between Intents .................................................................................. 22
Setting Complex Attributes ............................................................................................... 23
Deployment Options ................................................................................................................. 24
Built-in Intents and Slot Types ................................................................................................... 24
Built-in Intents ................................................................................................................. 24
Built-in Slot Types ............................................................................................................ 25
Custom Slot Types ................................................................................................................... 29
Getting Started ................................................................................................................................ 31
Step 1: Set Up an Account ........................................................................................................ 31
Sign Up for AWS .............................................................................................................. 31
Create an IAM User .......................................................................................................... 32
Next Step ........................................................................................................................ 32
Step 2: Set Up the AWS CLI ....................................................................................................... 32
...................................................................................................................................... 33
Step 3: Getting Started (Console) ............................................................................................... 33
Exercise 1: Create a Bot Using a Blueprint ........................................................................... 33
Exercise 2: Create a Custom Bot ......................................................................................... 60
Exercise 3: Publish a Version and Create an Alias .................................................................. 71
Step 4: Getting Started (AWS CLI) .............................................................................................. 72
Exercise 1: Create a Bot .................................................................................................... 72
Exercise 2: Add a New Utterance ........................................................................................ 84
Exercise 3: Add a Lambda Function .................................................................................... 88
Exercise 4: Publish a Version .............................................................................................. 91
Exercise 5: Create an Alias ................................................................................................. 95
Exercise 6: Clean Up ......................................................................................................... 96
Versioning and Aliases ...................................................................................................................... 97
Versioning ............................................................................................................................... 97
The $LATEST Version ........................................................................................................ 97
Publishing an Amazon Lex Resource Version ........................................................................ 97
Updating an Amazon Lex Resource ..................................................................................... 98
Deleting an Amazon Lex Resource or Version ....................................................................... 98
Aliases .................................................................................................................................... 99
Using Lambda Functions ................................................................................................................. 101
Lambda Function Input Event and Response Format ................................................................... 101

iii
Amazon Lex Developer Guide

Input Event Format ......................................................................................................... 101


Response Format ............................................................................................................ 104
Amazon Lex and AWS Lambda Blueprints .................................................................................. 108
Deploying Bots ............................................................................................................................... 109
Deploying an Amazon Lex Bot on a Messaging Platform .............................................................. 109
Integrating with Facebook ............................................................................................... 111
Integrating with Kik ........................................................................................................ 113
Integrating with Slack ..................................................................................................... 116
Integrating with Twilio SMS ............................................................................................. 120
Deploying an Amazon Lex Bot in Mobile Applications .................................................................. 123
Importing and Exporting ................................................................................................................. 124
Exporting and Importing in Amazon Lex Format ......................................................................... 124
Exporting in Amazon Lex Format ...................................................................................... 124
Importing in Amazon Lex Format ..................................................................................... 125
JSON Format for Importing and Exporting ......................................................................... 126
Exporting to an Alexa Skill ...................................................................................................... 128
Bot Examples ................................................................................................................................. 130
Example Bot: ScheduleAppointment ......................................................................................... 130
Overview of the Bot Blueprint (ScheduleAppointment) ........................................................ 132
Overview of the Lambda Function Blueprint (lex-make-appointment-python) ......................... 133
Step 1: Create an Amazon Lex Bot .................................................................................... 133
Step 2: Create a Lambda Function .................................................................................... 135
Step 3: Update the Intent: Configure a Code Hook .............................................................. 135
Step 4: Deploy the Bot on the Facebook Messenger Platform ............................................... 136
Details of Information Flow ............................................................................................. 137
Example Bot: BookTrip ............................................................................................................ 148
Step 1: Blueprint Review ................................................................................................. 149
Step 2: Create an Amazon Lex Bot .................................................................................... 151
Step 3: Create a Lambda function .................................................................................... 154
Step 4: Add the Lambda Function as a Code Hook .............................................................. 154
Details of the Information Flow ........................................................................................ 156
Example: Using a Response Card .............................................................................................. 170
Example: Updating Utterances ................................................................................................. 173
Example: Integrating with a Web site ........................................................................................ 174
Monitoring ..................................................................................................................................... 175
Monitoring Amazon Lex with CloudWatch .................................................................................. 175
CloudWatch Metrics for Amazon Lex ................................................................................. 175
Viewing Amazon Lex Metrics ............................................................................................ 175
Creating an Alarm .......................................................................................................... 176
Runtime Metrics for Amazon Lex ...................................................................................... 176
Channel Association Metrics for Amazon Lex ...................................................................... 179
Logging Amazon Lex API Calls with AWS CloudTrail .................................................................... 180
Amazon Lex Information in CloudTrail ............................................................................... 180
Example: Amazon Lex Log File Entries ............................................................................... 181
Guidelines and Limits ...................................................................................................................... 184
General Guidelines .................................................................................................................. 184
Limits .................................................................................................................................... 186
General Limits ................................................................................................................ 186
Runtime Service Limits .................................................................................................... 186
Model Building Limits .................................................................................................... 187
Authentication and Access Control .................................................................................................... 191
Authentication ....................................................................................................................... 191
Access Control ........................................................................................................................ 192
Overview of Managing Access .................................................................................................. 192
Amazon Lex Resources and Operations ............................................................................. 193
Understanding Resource Ownership .................................................................................. 193
Managing Access to Resources ......................................................................................... 193

iv
Amazon Lex Developer Guide

Specifying Policy Elements: Actions, Effects, and Principals .................................................. 194


Specifying Conditions in a Policy ...................................................................................... 195
Using Identity-Based Policies (IAM Policies) for Amazon Lex ......................................................... 196
Permissions Required to Use the Amazon Lex Console ......................................................... 197
AWS Managed (Predefined) Policies for Amazon Lex ........................................................... 199
Examples of Customer Managed Policies ........................................................................... 199
Amazon Lex API Permissions Reference ..................................................................................... 201
API Reference ................................................................................................................................. 202
Actions .................................................................................................................................. 202
Amazon Lex Model Building Service .................................................................................. 203
Amazon Lex Runtime Service ........................................................................................... 326
Data Types ............................................................................................................................ 340
Amazon Lex Model Building Service .................................................................................. 341
Amazon Lex Runtime Service ........................................................................................... 367
Document History .......................................................................................................................... 372
AWS Glossary ................................................................................................................................. 374

v
Amazon Lex Developer Guide

What Is Amazon Lex?


Amazon Lex is an AWS service for building conversational interfaces for applications using voice and
text. With Amazon Lex, the same conversational engine that powers Amazon Alexa is now available
to any developer, enabling you to build sophisticated, natural language chatbots into your new and
existing applications. Amazon Lex provides the deep functionality and flexibility of natural language
understanding (NLU) and automatic speech recognition (ASR) so you can build highly engaging user
experiences with lifelike, conversational interactions, and create new categories of products.

Amazon Lex enables any developer to build conversational chatbots quickly. With Amazon Lex, no deep
learning expertise is necessary—to create a bot, you just specify the basic conversation flow in the
Amazon Lex console. Amazon Lex manages the dialogue and dynamically adjusts the responses in the
conversation. Using the console, you can build, test, and publish your text or voice chatbot. You can then
add the conversational interfaces to bots on mobile devices, web applications, and chat platforms (for
example, Facebook Messenger).

Amazon Lex provides pre-built integration with AWS Lambda, and you can easily integrate with many
other services on the AWS platform, including Amazon Cognito, AWS Mobile Hub, Amazon CloudWatch,
and Amazon DynamoDB. Integration with Lambda provides bots access to pre-built serverless enterprise
connectors to link to data in SaaS applications, such as Salesforce, HubSpot, or Marketo.

Some of the benefits of using Amazon Lex include:

• Simplicity – Amazon Lex guides you through using the console to create your own chatbot in minutes.
You supply just a few example phrases, and Amazon Lex builds a complete natural language model
through which the bot can interact using voice and text to ask questions, get answers, and complete
sophisticated tasks.

 
• Democratized deep learning technologies – Powered by the same technology as Alexa, Amazon
Lex provides ASR and NLU technologies to create a Speech Language Understanding (SLU) system.
Through SLU, Amazon Lex takes natural language speech and text input, understands the intent
behind the input, and fulfills the user intent by invoking the appropriate business function.

Speech recognition and natural language understanding are some of the most challenging problems
to solve in computer science, requiring sophisticated deep learning algorithms to be trained on
massive amounts of data and infrastructure. Amazon Lex puts deep learning technologies within reach
of all developers, powered by the same technology as Alexa. Amazon Lex chatbots convert incoming
speech to text and understand the user intent to generate an intelligent response, so you can focus on
building your bots with differentiated value-add for your customers, to define entirely new categories
of products made possible through conversational interfaces.

 
• Seamless deployment and scaling – With Amazon Lex, you can build, test, and deploy your chatbots
directly from the Amazon Lex console. Amazon Lex enables you to easily publish your voice or text
chatbots for use on mobile devices, web apps, and chat services (for example, Facebook Messenger).
Amazon Lex scales automatically so you don’t need to worry about provisioning hardware and
managing infrastructure to power your bot experience.

 
• Built-in integration with the AWS platform – Amazon Lex has native interoperability with other AWS
services, such as Amazon Cognito, AWS Lambda, Amazon CloudWatch, and AWS Mobile Hub. You

1
Amazon Lex Developer Guide
Are You a First-time User of Amazon Lex?

can take advantage of the power of the AWS platform for security, monitoring, user authentication,
business logic, storage, and mobile app development.

 
• Cost-effectiveness – With Amazon Lex, there are no upfront costs or minimum fees. You are charged
only for the text or speech requests that are made. The pay-as-you-go pricing and the low cost per
request make the service a cost-effective way to build conversational interfaces. With the Amazon Lex
free tier, you can easily try Amazon Lex without any initial investment.

Are You a First-time User of Amazon Lex?


If you are a first-time user of Amazon Lex, we recommend that you read the following sections in order:

1. Getting Started with Amazon Lex (p. 31) – In this section, you set up your account and test
Amazon Lex.
2. API Reference (p. 202) – This section provides additional examples that you can use to explore
Amazon Lex.

2
Amazon Lex Developer Guide

Amazon Lex: How It Works


Amazon Lex enables you to build applications using a speech or text interface powered by the same
technology that powers Amazon Alexa. Following are the typical steps you perform when working with
Amazon Lex:

1. Create a bot and configure it with one or more intents that you want to support. Configure the bot so
it understands the user's goal (intent), engages in conversation with the user to elicit information, and
fulfills the user's intent.
2. Test the bot. You can use the test window client provided by the Amazon Lex console.
3. Publish a version and create an alias.
4. Deploy the bot. You can deploy the bot on platforms such as mobile applications or messaging
platforms such as Facebook Messenger.

Before you get started, familiarize yourself with the following Amazon Lex core concepts and
terminology:

• Bot – A bot performs automated tasks such as ordering a pizza, booking a hotel, ordering flowers, and
so on. An Amazon Lex bot is powered by Automatic Speech Recognition (ASR) and Natural Language
Understanding (NLU) capabilities, the same technology that powers Amazon Alexa.

Amazon Lex bots can understand user input provided with text or speech and converse in natural
language. You can create Lambda functions and add them as code hooks in your intent configuration
to perform user data validation and fulfillment tasks.

 
• Intent – An intent represents an action that the user wants to perform. You create a bot to support
one or more related intents. For example, you might create a bot that orders pizza and drinks. For each
intent, you provide the following required information:

 
• Intent name– A descriptive name for the intent. For example, OrderPizza.
• Sample utterances – How a user might convey the intent. For example, a user might say "Can I order
a pizza please" or "I want to order a pizza".
• How to fulfill the intent – How you want to fulfill the intent after the user provides the necessary
information (for example, place order with a local pizza shop). We recommend that you create a
Lambda function to fulfill the intent.

You can optionally configure the intent so Amazon Lex simply returns the information back to the
client application to do the necessary fulfillment.

In addition to custom intents such as ordering a pizza, Amazon Lex also provides built-in intents to
quickly set up your bot. For more information, see Built-in Intents and Slot Types (p. 24).

 
• Slot – An intent can require zero or more slots or parameters. You add slots as part of the intent
configuration. At runtime, Amazon Lex prompts the user for specific slot values. The user must provide
values for all required slots before Amazon Lex can fulfill the intent.

3
Amazon Lex Developer Guide
Programming Model

For example, the OrderPizza intent requires slots such as pizza size, crust type, and number of
pizzas. In the intent configuration, you add these slots. For each slot, you provide slot type and a
prompt for Amazon Lex to send to the client to elicit data from the user. A user can reply with a slot
value that includes additional words, such as "large pizza please" or "let's stick with small." Amazon Lex
can still understand the intended slot value.

 
• Slot type – Each slot has a type. You can create your custom slot types or use built-in slot types. For
example, you might create and use the following slot types for the OrderPizza intent:

 
• Size – With enumeration values Small, Medium, and Large.
• Crust – With enumeration values Thick and Thin.

Amazon Lex also provides built-in slot types. For example, AMAZON.NUMBER is a built-in slot type that
you can use for the number of pizzas ordered. For more information, see Built-in Intents and Slot
Types (p. 24).

The following topics provide additional information. We recommend that you review them in order and
then explore the Getting Started with Amazon Lex (p. 31) exercises.

Topics
• Programming Model (p. 4)
• Service Permissions (p. 8)
• Managing Messages (p. 9)
• Managing Conversation Context (p. 19)
• Bot Deployment Options (p. 24)
• Built-in Intents and Slot Types (p. 24)
• Custom Slot Types (p. 29)

Programming Model
A bot is the primary resource type in Amazon Lex. The other resource types in Amazon Lex are intent, slot
type, alias, and bot channel association.

You create a bot using the Amazon Lex console or the model building API. The console provides a
graphical user interface that you use to build a production-ready bot for your application. If you prefer,
you can use the model building API through the AWS CLI or your own custom program to create a bot.

After you create a bot, you deploy it on one of the supported platforms or integrate it into your own
application. When a user interacts with the bot, the client application sends requests to the bot using
the Amazon Lex runtime API. For example, when a user says "I want to order pizza," your client sends this
input to Amazon Lex using one of the runtime API operations. Users can provide input as speech or text.

You can also create Lambda functions and use them in an intent. Use these Lambda function code hooks
to perform runtime activities such as initialization, validation of user input, and intent fulfillment. The
following sections provide additional information.

Topics

4
Amazon Lex Developer Guide
Model Building API Operations

• Model Building API Operations (p. 5)


• Runtime API Operations (p. 5)
• Lambda Functions As Code Hooks (p. 6)

Model Building API Operations


To programmatically create bots, intents, and slot types, use the model building API operations. You
can also use the model building API to manage, update, and delete resources for your bot. The model
building API operations include:

• PutBot (p. 297), PutBotAlias (p. 305), PutIntent (p. 309), and PutSlotType (p. 319) to create and
update bots, bot aliases, intents, and slot types, respectively.
• CreateBotVersion (p. 205), CreateIntentVersion (p. 210), and CreateSlotTypeVersion (p. 216) to
create and publish versions of your bots, intents, and slot types, respectively.
• GetBot (p. 238) and GetBots (p. 256) to get a specific bot or a list of bots that you have created,
respectively.
• GetIntent (p. 274) and GetIntents (p. 279) to get a specific intent or a list of intents that you have
created, respectively.
• GetSlotType (p. 285) and GetSlotTypes (p. 288) to get a specific slot type or a list of slot types that
you have created, respectively.
• GetBuiltinIntent (p. 262), GetBuiltinIntents (p. 264), and GetBuiltinSlotTypes (p. 266) to get an
Amazon Lex built-in intent, a list of Amazon Lex built-in intents, or a list of built-in slot types that you
can use in your bot, respectively.
• GetBotChannelAssociation (p. 249) and GetBotChannelAssociations (p. 253) to get an association
between your bot and a messaging platform or a list of the associations between your bot and
messaging platforms, respectively.
• DeleteBot (p. 220), DeleteBotAlias (p. 222), DeleteBotChannelAssociation (p. 224),
DeleteIntent (p. 228), and DeleteSlotType (p. 232) to remove unneeded resources in your account.

You can use the model building API to create custom tools to manage your Amazon Lex resources. For
example, there is a limit of 100 versions each for bots, intents, and slot types. You could use the model
building API to build a tool that automatically deletes old versions when your bot nears the limit.

To make sure that only one operation updates a resource at a time, Amazon Lex uses checksums.
When you use a Put API operation—PutBot (p. 297), PutBotAlias (p. 305) PutIntent (p. 309), or
PutSlotType (p. 319)—to update a resource, you must pass the current checksum of the resource
in the request. If two tools try to update a resource at the same time, they both provide the same
current checksum. The first request to reach Amazon Lex matches the current checksum of the resource.
By the time that the second request arrives, the checksum is different. The second tool receives a
PreconditionFailedException exception and the update terminates.

The Get operations—GetBot (p. 238), GetIntent (p. 274), and GetSlotType (p. 285)—are eventually
consistent. If you use a Get operation immediately after you create or modify a resource with one of
the Put operations, the changes might not be returned. After a Get operation returns the most recent
update, it always returns that updated resource until the resource is modified again. You can determine if
an updated resource has been returned by looking at the checksum.

Runtime API Operations


Client applications use the following runtime API operations to communicate with Amazon Lex:

• PostContent (p. 327) – Takes speech or text input and returns intent information and a text or speech
message to convey to the user. Currently, Amazon Lex supports the following audio formats:

5
Amazon Lex Developer Guide
Lambda Functions As Code Hooks

Input audio formats – LPCM and Opus

Output audio formats – MPEG, OGG, and PCM

The PostContent operation supports audio input at 8 kHz and 16 kHz. Applications where the end
user speaks with Amazon Lex over the telephone, such as an automated call center, can pass 8 kHz
audio directly.

 
• PostText (p. 335) – Takes text as input and returns intent information and a text message to convey
to the user.

Your client application uses the runtime API to call a specific Amazon Lex bot to process utterances —
user text or voice input. For example, suppose that a user says "I want pizza." The client sends this user
input to a bot using one of the Amazon Lex runtime API operations. From the user input, Amazon Lex
recognizes that the user request is for the OrderPizza intent defined in the bot. Amazon Lex engages
the user in a conversation to gather the required information, or slot data, such as pizza size, toppings,
and number of pizzas. After the user provides all of the necessary slot data, Amazon Lex either invokes
the Lambda function code hook to fulfill the intent, or returns the intent data to the client, depending
on how the intent is configured.

Use the PostContent (p. 327) operation when your bot uses speech input. For example, an automated
call center application can send speech to an Amazon Lex bot instead of an agent to address customer
inquiries. You can use the 8 kHz audio format to send audio directly from the telephone to Amazon Lex.

The test window in the Amazon Lex console uses the PostContent (p. 327) API to send text and speech
requests to Amazon Lex. You use this test window in the Getting Started with Amazon Lex (p. 31)
exercises.

Lambda Functions As Code Hooks


You can configure your Amazon Lex bot to invoke a Lambda function as a code hook. The code hook can
serve multiple purposes:

• Customizes the user interaction—For example, when Joe asks for available pizza toppings, you can use
prior knowledge of Joe's choices to display a subset of toppings.
• Validates the user's input—Suppose that Jen wants to pick up flowers after hours. You can validate the
time that Jen input and send an appropriate response.
• Fulfills the user's intent—After Joe provides all of the information for his pizza order, Amazon Lex can
invoke a Lambda function to place the order with a local pizzeria.

When you configure an intent, you specify Lambda functions as code hooks in the following places:

• Dialog code hook for initialization and validation—This Lambda function is invoked on each user input,
assuming Amazon Lex understood the user intent.
• Fulfillment code hook—This Lambda function is invoked after the user provides all of the slot data
required to fulfill the intent.

You choose the intent and set the code hooks in the Amazon Lex console, as shown in the following
screen shot:

6
Amazon Lex Developer Guide
Lambda Functions As Code Hooks

7
Amazon Lex Developer Guide
Service Permissions

You can also set the code hooks using the dialogCodeHook and fulfillmentActivity fields in the
PutIntent (p. 309) operation.

One Lambda function can perform initialization, validation, and fulfillment. The event data that the
Lambda function receives has a field that identifies the caller as either a dialog or fulfillment code hook.
You can use this information to execute the appropriate portion of your code.

You can use a Lambda function to build a bot that can navigate complex dialogs. You use the
dialogAction field in the Lambda function response to direct Amazon Lex to take specific actions. For
example, you can use the ElicitSlot dialog action to tell Amazon Lex to ask the user for a slot value
that isn't required. You can use the ElicitIntent dialog action to elicit a new intent when the user is
finished with the previous one.

For more information, see Using Lambda Functions (p. 101).

Service Permissions
Amazon Lex uses AWS Identity and Access Management (IAM) service-linked roles. Amazon Lex assumes
these roles to call AWS services on behalf of your bots and bot channels. The roles exist within your
account, but are linked to Amazon Lex use cases and have predefined permissions. Only Amazon Lex
can assume these roles, and you can't modify their permissions. You can delete them after deleting their
related resources using IAM. This protects your Amazon Lex resources because you can't inadvertently
remove necessary permissions.

Amazon Lex uses two IAM service-linked roles:

• AWSServiceRoleForLexBots—Amazon Lex uses this service-linked role to invoke Amazon Polly to


synthesize speech responses for your bot.
• AWSServiceRoleForLexChannels—Amazon Lex uses this service-linked role to post text to your bot
when managing channels.

You don't need to manually create either of these roles. When you create your first bot using the console,
Amazon Lex creates the AWSServiceRoleForLexBots role for you. When you first associate a bot with a
messaging channel, Amazon Lex creates the AWSServiceRoleForLexChannels role for you.

Creating Resource-Based Policies for AWS Lambda


When invoking Lambda functions, Amazon Lex uses resource-based policies. A resource-based policy is
attached to a resource; it lets you specify who has access to the resource and which actions they can
perform on it. This enables you to narrowly scope permissions between Lambda functions and the
intents that you have created. It also allows you to see those permissions in a single policy when you
manage Lambda functions that have many event sources.

For more information, see Using Resource-Based Polices for AWS Lambda (Lambda Function Policies) in
the AWS Lambda Developer Guide.

To create resource-based policies for intents that you associate with a Lambda function, you can use the
Amazon Lex console. Or, you can use the AWS command line interface (AWS CLI). In the AWS CLI, use the
Lambda AddPermisssion API with the Principal field set to lex.amazonaws.com and the SourceArn
set to the ARN of the intent that is allowed to invoke the function.

Deleting Service-Linked Roles


You can use the IAM console, the IAM CLI, or the IAM API to delete the AWSServiceRoleForLexBots
and AWSServiceRoleForLexChannels service-linked roles. For more information, see Deleting a
Service-Linked Role in the IAM User Guide.

8
Amazon Lex Developer Guide
Managing Messages

Managing Messages
Topics
• Types of Messages (p. 9)
• Contexts for Configuring Messages (p. 10)
• Supported Message Formats (p. 14)
• Message Groups (p. 14)
• Response Cards (p. 15)

When you create a bot, you can configure clarifying or informational messages that you want it to send
to the client. Consider the following examples:

• You could configure your bot with the following clarification prompt:

I don't understand. What would you like to do?

Amazon Lex sends this message to the client if it doesn't understand the user's intent.

 
• Suppose that you create a bot to support an intent called OrderPizza. For a pizza order, you want
users to provide information such as pizza size, toppings, and crust type. You could configure the
following prompts:

What size pizza do you want?


What toppings do you want?
Do you want thick or thin crust?

After Amazon Lex determines the user's intent to order pizza, it sends these messages to the client to
get information from the user.

This section explains designing user interactions in your bot configuration.

Types of Messages
A message can be a prompt or a statement.

• A prompt is typically a question and expects a user response.


• A statement is informational. It doesn’t expect a response.

A message can include references to slot and session attributes. At runtime, Amazon Lex substitutes
these references with actual values.

To refer to slots values that have been set, use the following syntax:

{SlotName}

To refer to session attributes, use the following syntax:

[AttributeName]

9
Amazon Lex Developer Guide
Contexts for Configuring Messages

Messages can include both slot values and session attributes.

For example, suppose that you configure the following message in your bot's OrderPizza intent:

"Hey [FirstName], your {PizzaTopping} pizza will arrive in [DeliveryTime] minutes."

This message refers to both slot (PizzaTopping) and session attributes (FirstName and
DeliveryTime). At runtime, Amazon Lex replaces these placeholders with values and returns the
following message to the client:

"Hey John, your cheese pizza will arrive in 30 minutes."

To include brackets ([]) or braces ({}) in a message, use the backslash (\) escape character. For example,
the following message includes the curly braces and square brackets:

\{Text\} \[Text\]

The text returned to the client application looks like this:

{Text} [Text]

For information about session attributes, see the runtime API operations PostText (p. 335) and
PostContent (p. 327). For an example, see Example Bot: BookTrip (p. 148).

Lambda functions can also generate messages and return them to Amazon Lex to send to the user. If
you add Lambda functions when you configure your intent, you can create messages dynamically. By
providing the messages while configuring your bot, you can eliminate the need to construct a prompt in
your Lambda function.

Contexts for Configuring Messages


When you are creating your bot, you can create messages in different contexts, such as clarification
prompts in bot, prompts for slot values, and messages from intents. Amazon Lex chooses an appropriate
message in each context to return to your user. You can provide a group of messages for each context.
If you do, Amazon Lex randomly chooses one message from the group. You can also specify the
format of the message or group the messages together. For more information, see Supported Message
Formats (p. 14).

If you have a Lambda function associated with an intent, you can override any of the messages that you
configured at build time. A Lambda function is not required to use any of these messages, however.

Bot Messages
You can configure your bot with clarification prompts and hang-up messages. At runtime, Amazon Lex
uses the clarification prompt if it doesn't understand the user's intent. You can configure the number
of times that Amazon Lex requests clarification before hanging up with the hang-up message. You
configure bot-level messages in the Error Handling section of the Amazon Lex console, as follows:

10
Amazon Lex Developer Guide
Contexts for Configuring Messages

With the API, you configure messages by setting the clarificationPrompt and abortStatement
fields in the PutBot (p. 297) operation.

If you use a Lambda function with an intent, the Lambda function might return a response directing
Amazon Lex to ask a user's intent. If the Lambda function doesn’t provide such a message, Amazon Lex
uses the clarification prompt.

Slot Prompts
You must specify at least one prompt message for each of the required slots in an intent. At runtime,
Amazon Lex uses one of these messages to prompt the user to provide a value for the slot. For example,
for a cityName slot, the following is a valid prompt:

Which city would you like to fly to?

You can set one or more prompts for each slot using the console. You can also create groups of prompts
using the PutIntent (p. 309) operation. For more information, see Message Groups (p. 14).

Responses
In the console, use the Responses section to build dynamic, engaging conversations for your bot. You
can create one or more message groups for a response. At runtime, Amazon Lex builds a response by
selecting one message from each message group. For more information about message groups, see
Message Groups (p. 14).

For example, your first message group could contain different greetings: "Hello," "Hi," and "Greetings."
The second message group could contain different forms of introduction: "I am the reservation bot" and
"This is the reservation bot." A third message group could communicate the bot's capabilities: "I can help
with car rentals and hotel reservations," "You can make car rentals and hotel reservations," and "I can
help you rent a car and book a hotel."

Lex uses a message from each of the message groups to dynamically build the responses in a
conversation. For example, one interaction could be:

11
Amazon Lex Developer Guide
Contexts for Configuring Messages

Another one could be:

In either case, the user could respond with a new intent, such as the BookCar or BookHotel intent.

You can set up the bot to ask a follow-up question in the response. For example, for the preceding
interaction, you could create a fourth message group with the following questions: "Can I help with a car
or a hotel?", "Would you like to make a reservation now?", and "Is there anything that I can do for you?".
For messages that include "No" as a response, you can create a follow-up prompt. For example:

12
Amazon Lex Developer Guide
Contexts for Configuring Messages

To create a follow-up prompt, choose Wait for user reply. Then type the message or messages that you
want to send when the user says "No." When you create a response to use as a follow-up prompt, you
must also specify an appropriate statement when the answer to the statement is "No." For example:

To add responses to an intent with the API, use the PutIntent operation. To specify a response,
set the conclusionStatement field in the PutIntent request. To set a follow-up prompt, set the

13
Amazon Lex Developer Guide
Supported Message Formats

followUpPrompt field and include the statement to send when the user says "No." You can't set both
the conclusionStatement field and the followUpPrompt field on the same intent.

Supported Message Formats


When you use the PostText (p. 335) operation, or when you use the PostContent (p. 327) operation
with the Accept header set to text/plain;charset=utf8, Amazon Lex supports messages in the
following formats:

• PlainText—The message contains plain UTF-8 text.


• SSML—The message contains text formatted for voice output.
• CustomPayload—The message contains a custom format that you have created for your client. You
can define the payload to meet the needs of your application.
• Composite—The message is a collection of messages, one from each message group. For more
information about message groups, see Message Groups (p. 14).

By default, Amazon Lex returns any one of the messages defined for a particular prompt. For example, if
you define five messages to elicit a slot value, Amazon Lex chooses one of the messages randomly and
returns it to the client.

If you want Amazon Lex to return a specific type of message to the client in a run-time request, set
the x-amzn-lex:accept-content-types request parameter. The response is limited to the type or
types requested. If there is more than one message of the specified type, Amazon Lex returns one at
random. For more information about the x-amz-lex:accept-content-types header, see Setting the
Response Type (p. 21).

Message Groups
A message group is a set of suitable responses to a particular prompt. Use message groups when
you want your bot to dynamically build the responses in a conversation. When Amazon Lex returns a
response to the client application, it randomly chooses one message from each group. You can create
a maximum of five message groups for each response. Each group can contain a maximum of five
messages. For examples of creating message groups in the console, see Responses (p. 11).

To create a message group, you can use the console or you can use the PutBot (p. 297),
PutIntent (p. 309), or PutSlotType (p. 319) operations to assign a group number to a message. If
you don't create a message group, or if you create only one message group, Amazon Lex sends a single
message in the Message field. Client applications get multiple messages in a response only when you
have created more than one message group in the console, or when you create more than one message
group when you create or update an intent with the PutIntent (p. 309) operation.

When Amazon Lex sends a message from a group, the response's Message field contains an escaped
JSON object that contains the messages. The following example shows the contents of the Message
field when it contains multiple messages.
Note
The example is formatted for readability. A response doesn't contain carriage returns (CR).

{\"messages\":[
{\"type\":\"PlainText\",\"group\":0,\"value\":\"Plain text\"},
{\"type\":\"SSML\",\"group\":1,\"value\":\"SSML text\"},
{\"type\":\"CustomPayload\",\"group\":2,\"value\":\"Custom payload\"}
]}

You can set the format of the messages. The format can be one of the following:

14
Amazon Lex Developer Guide
Response Cards

• PlainText—The message is in plain UTF-8 text.


• SSML—The message is Speech Synthesis Markup Language (SSML).
• CustomPayload—The message is in a custom format that you specified.

To control the format of messages that the PostContent and PostText operations return in the
Message field, set the x-amz-lex:accept-content-types request attribute. For example, if you set
the header to the following, you receive only plain text and SSML messages in the response:

x-amz-lex:accept-content-types: PlainText,SSML

If you request a specific message format and a message group doesn't contain that a message with that
format, you get a NoUsableMessageException exception. When you use a message group to group
messages by type, don't use the x-amz-lex:accept-content-types header.

For more information about the x-amz-lex:accept-content-types header, see Setting the
Response Type (p. 21).

Response Cards
A response card contains a set of appropriate responses to a prompt. Use response cards to simplify
interactions for your users and increase your bot's accuracy by reducing typographical errors in text
interactions. You can send a response card for each prompt that Amazon Lex sends to your client
application. You can use response cards with Facebook Messenger, Slack, Twilio, and your own client
applications.

For example, in a taxi application, you can configure an option in the response card for "Home" and set
the value to the user's home address. When the user selects this option, Amazon Lex receives the entire
address as the input text.

You can define a response card for the following prompts:

• Conclusion statement
• Confirmation prompt
• Follow-up prompt
• Rejection statement
• Slot type utterances

You can define only one response card for each prompt.

You configure response cards when you create an intent. You can define a static response card at build
time using the console or the PutIntent (p. 309) operation. Or you can define a dynamic response card

15
Amazon Lex Developer Guide
Response Cards

at runtime in a Lambda function. If you define both static and dynamic response cards, the dynamic
response card takes precedence.

Amazon Lex sends response cards in the format that the client understands. It transforms response cards
for Facebook Messenger, Slack, and Twilio. For other clients, Amazon Lex sends a JSON structure in the
PostText (p. 335) response. For example, if the client is Facebook Messenger, Amazon Lex transforms
the response card to a generic template. For more information about Facebook Messenger generic
templates, see Generic Template on the Facebook website. For an example of the JSON structure, see
Generating Response Cards Dynamically (p. 18).

You can use response cards only with the PostText (p. 335) operation. You can't use response cards with
the PostContent (p. 327) operation.

Defining Static Response Cards


Define static response cards with the PutBot (p. 297) operation or the Amazon Lex console when you
create an intent. A static response card is defined at the same time as the intent. Use a static response
card when the responses are fixed. Suppose that you are creating a bot with an intent that has a slot for
flavor. When defining the flavor slot, you specify prompts, as shown in the following console screenshot:

When defining prompts, you can optionally associate a response card and define details with the
PutBot (p. 297) operation, or, in the Amazon Lex console, as shown in the following example:

16
Amazon Lex Developer Guide
Response Cards

Now suppose that you've integrated your bot with Facebook Messenger. The user can click the buttons to
choose a flavor, as shown in the following illustration:

17
Amazon Lex Developer Guide
Response Cards

To customize the content of a response card, you can refer to session attributes. At runtime, Amazon Lex
substitutes these references with appropriate values from the session attributes. For more information,
see Setting Session Attributes (p. 19). For an example, see Example: Using a Response Card (p. 170).

Generating Response Cards Dynamically


To generate response cards dynamically at runtime, use the initialization and validation Lambda function
for the intent. Use a dynamic response card when the responses are determined at runtime in the
Lambda function. In response to user input, the Lambda function generates a response card and returns
it in the dialogAction section of the response. For more information, see Response Format (p. 104).

The following is a partial response from a Lambda function that shows the responseCard element. It
generates a user experience similar to the one shown in the preceding section.

responseCard: {
"version": 1,
"contentType": "application/vnd.amazonaws.card.generic",
"genericAttachments": [
{
"title": "What Flavor?",
"subtitle": "What flavor do you want?",
"imageUrl": "Link to image",
"attachmentLinkUrl": "Link to attachment",
"buttons": [
{

18
Amazon Lex Developer Guide
Managing Conversation Context

"text": "Lemon",
"value": "lemon"
},
{
"text": "Raspberry",
"value": "raspberry"
},
{
"text": "Plain",
"value": "plain"
}
]
}
]
}

For an example, see Example Bot: ScheduleAppointment (p. 130).

Managing Conversation Context


Conversation context is the information that a user, your application, or a Lambda function provides to
an Amazon Lex bot to fulfill an intent. Conversation context includes slot data that the user provides,
request attributes set by the client application, and session attributes that the client application and
Lambda functions create.

Topics
• Setting Session Attributes (p. 19)
• Setting Request Attributes (p. 20)
• Setting the Session Timeout (p. 22)
• Sharing Information Between Intents (p. 22)
• Setting Complex Attributes (p. 23)

Setting Session Attributes


Session attributes contain application-specific information that is passed between a bot and a client
application during a session. Amazon Lex passes session attributes to all Lambda functions configured
for a bot. If a Lambda function adds or updates session attributes, Amazon Lex passes the new
information back to the client application. For example:

• In Exercise 1: Create an Amazon Lex Bot Using a Blueprint (Console) (p. 33), the example bot uses
the price session attribute to maintain the price of flowers. The Lambda function sets this attribute
based on the type of flowers that was ordered. For more information, see Step 5 (Optional): Review
the Details of the Information Flow (Console) (p. 48).
• In Example Bot: BookTrip (p. 148), the example bot uses the currentReservation session
attribute to maintain a copy of the slot type data during the conversation to book a hotel or to book a
rental car. For more information, see Details of the Information Flow (p. 156).

Use session attributes in your Lambda functions to initialize a bot and to customize prompts and
response cards. For example:

• Initialization — In a pizza ordering bot, the client application passes the user's location as a session
attribute in the first call to the PostContent (p. 327) or PostText (p. 335) operation. For example,
"Location": "111 Maple Street". The Lambda function uses this information to find the closest
pizzeria to place the order.

19
Amazon Lex Developer Guide
Setting Request Attributes

• Personalize prompts — Configure prompts and response cards to refer to session attributes. For
example, "Hey [FirstName], what toppings would you like?" If you pass the user's first name as a
session attribute ({"FirstName": "Jo"}), Amazon Lex substitutes the name for the placeholder. It
then sends a personalized prompt to the user, "Hey Jo, which toppings would you like?"

Session attributes persist for the duration of the session. Amazon Lex stores them in an encrypted data
store until the session ends. The client can create session attributes in a request by calling either the
PostContent (p. 327) or the PostText (p. 335) operation with the sessionAttributes field set to
a value. A Lambda function can create a session attribute in a response. After the client or a Lambda
function creates a session attribute, the stored attribute value is used any time that the client application
doesn't include sessionAttribute field in a request to Amazon Lex.

For example, suppose you have two session attributes, {"x": "1", "y": "2"}. If the client calls the
PostContent or PostText operation without specifying the sessionAttributes field, Amazon
Lex calls the Lambda function with the stored session attributes ({"x": 1, "y": 2}). If the Lambda
function doesn't return session attributes, Amazon Lex returns the stored session attributes to the client
application.

If either the client application or a Lambda function passes session attributes, Amazon Lex updates the
stored session attributes. Passing an existing value, such as {"x": 2}, updates the stored value. If you
pass a new set of session attributes, such as {"z": 3}, the existing values are removed and only the
new value is kept. When an empty map, {}, is passed, stored values are erased.

To send session attributes to Amazon Lex, you create a string-to-string map of the attributes. The
following shows how to map session attributes:

{
"attributeName": "attributeValue",
"attributeName": "attributeValue"
}

For the PostText operation, you insert the map into the body of the request using the
sessionAttributes field, as follows:

"sessionAttributes": {
"attributeName": "attributeValue",
"attributeName": "attributeValue"
}

For the PostContent operation, you base64 encode the map, and then send it as the x-amz-lex-
session-attributes header.

If you are sending binary or structured data in a session attribute, you must first transform the data to a
simple string. For more information, see Setting Complex Attributes (p. 23).

Setting Request Attributes


Request attributes contain request-specific information and apply only to the current request. A client
application sends this information to Amazon Lex. Use request attributes to pass information that
doesn't need to persist for the entire session. You can create your own request attributes or you can
use predefined attributes. To send request attributes, use the x-amz-lex-request-attributes
header in a the section called “PostContent” (p. 327) or the requestAttributes field in a the section
called “PostText” (p. 335) request. Because request attributes don't persist across requests like session
attributes do, they are not returned in PostContent or PostText responses.
Note
To send information that persists across requests, use session attributes.

20
Amazon Lex Developer Guide
Setting Request Attributes

The namespace x-amz-lex: is reserved for the predefined request attributes. Don't create request
attributes with the prefix x-amz-lex:.

Setting Predefined Request Attributes


Amazon Lex provides predefined request attributes for managing the way that it processes information
sent to your bot. The attributes do not persist for the entire session, so you must send the predefined
attributes in each request. All predefined attributes are in the x-amz-lex: namespace.

In addition to the following predefined attributes, Amazon Lex provides predefined attributes for
messaging platforms. For a list of those attributes, see Deploying an Amazon Lex Bot on a Messaging
Platform (p. 109).

Setting the Response Type


If you have two client applications that have different capabilities, you may need to limit the format of
messages in a response. For example, you might want to restrict messages sent to a Web client to plain
text, but enable a mobile client to use both plain text and Speech Synthesis Markup Language (SSML).
To set the format of messages returned by the PostContent (p. 327) and PostText (p. 335) operations,
use the x-amz-lex:accept-content-types" request attribute.

You can set the attribute to any combination of the following message types:

• PlainText—The message contains plain UTF-8 text.


• SSML—The message contains text formatted for voice output.
• CustomPayload—The message contains a custom format that you have created for your client. You
can define the payload to meet the needs of your application.

Amazon Lex returns only messages with the specified type in the Message field of the response. You
can set more than one value by separating values with a comma. If you are using message groups,
every message group must contain at least one message of the specified type. Otherwise, you get a
NoUsableMessageException error. For more information, see Message Groups (p. 14).
Note
The x-amz-lex:accept-content-types request attribute has no effect on the contents of
the HTML body. The contents of a PostText operation response is always plain UTF-8 text.
The body of a PostContent operation response contains data in the format set in the Accept
header in the request.

Setting the Preferred Time Zone


To set the time zone used to resolve dates so that it is relative to the user's time zone, use the x-amz-
lex:time-zone request attribute. If you do not specify a time zone in the x-amz-lex:time-zone
attribute, the default depends on the region that you are using for your bot.

Region Default time zone

US East (N. Virginia) America/New_York

US West (Oregon) America/Los_Angeles

EU (Ireland) Europe/Dublin

For example, if the user responds tomorrow in response to the prompt "Which day would you like your
package delivered?" the actual date that the package is delivered depends on the user's time zone. For
example, when it is 01:00 September 16 in New York, it is 22:00 September 15 in Los Angeles. If a person

21
Amazon Lex Developer Guide
Setting the Session Timeout

in Los Angeles orders a package to be delivered "tomorrow" using the default time zone, the package
would be delivered on the 17th, not the 16th. However, if you set the x-amz-lex:time-zone request
attribute to America/Los_Angeles, the package would be delivered on the 16th.

You can set the attribute to any of the Internet Assigned Number Authority (IANA) time zone names. For
the list of time zone names, see the List of tz database time zones on Wikipedia.

Setting User-Defined Request Attributes


A user-defined request attribute is data that you send to your bot in each request. You send the
information in the amz-lex-request-attributes header of a PostContent request or in the
requestAttributes field of a PostText request.

To send request attributes to Amazon Lex, you create a string-to-string map of the attributes. The
following shows how to map request attributes:

{
"attributeName": "attributeValue",
"attributeName": "attributeValue"
}

For the PostText operation, you insert the map into the body of the request using the
requestAttributes field, as follows:

"requestAttributes": {
"attributeName": "attributeValue",
"attributeName": "attributeValue"
}

For the PostContent operation, you base64 encode the map, and then send it as the x-amz-lex-
request-attributes header.

If you are sending binary or structured data in a request attribute, you must first transform the data to a
simple string. For more information, see Setting Complex Attributes (p. 23).

Setting the Session Timeout


Amazon Lex retains context information—slot data and session attributes—until a conversation session
ends. To control how long a session lasts for a bot, set the session timeout. By default, session duration is
5 minutes, but you can specify any duration between 0 and 1,440 minutes (24 hours).

For example, suppose that you create a ShoeOrdering bot that supports intents such as OrderShoes
and GetOrderStatus. When Amazon Lex detects that the user's intent is to order shoes, it asks for slot
data. For example, it asks for shoe size, color, brand, etc. If the user provides some of the slot data but
doesn't complete the shoe purchase, Amazon Lex remembers all of the slot data and session attributes
for the entire session. If the user returns to the session before it expires, he or she can provide the
remaining slot data, and complete the purchase.

In the Amazon Lex console, you set the session timeout when you create a bot. With the AWS
command line interface (AWS CLI) or API, you set the timeout when you create or update a bot with the
PutBot (p. 297) operation by setting the idleSessionTTLInSeconds field.

Sharing Information Between Intents


Amazon Lex supports sharing information between intents. To share between intents, use session
attributes.

22
Amazon Lex Developer Guide
Setting Complex Attributes

For example, a user of the ShoeOrdering bot starts by ordering shoes. The bot engages in a
conversation with the user, gathering slot data, such as shoe size, color, and brand. When the user places
an order, the Lambda function that fulfills the order sets the orderNumber session attribute, which
contains the order number. To get the status of the order, the user uses the GetOrderStatus intent.
The bot can ask the user for slot data, such as order number and order date. When the bot has the
required information, it returns the status of the order.

If you think that your users might switch intents during the same session, you can design your bot to
return the status of the latest order. Instead of asking the user for order information again, you use the
orderNumber session attribute to share information across intents and fulfill the GetOrderStatus
intent. The bot does this by returning the status of the last order that the user placed.

For an example of cross-intent information sharing, see Example Bot: BookTrip (p. 148).

Setting Complex Attributes


Session and request attributes are string-to-string maps of attributes and values. In many cases, you can
use the string map to transfer attribute values between your client application and a bot. In some cases,
however, you might need to transfer binary data or a complex structure that can't be easily converted
to a string map. For example, the following JSON object represents an array of the three most populous
cities in the United States:

{
"cities": [
{
"city": {
"name": "New York",
"state": "New York",
"pop": "8537673"
}
},
{
"city": {
"name": "Los Angeles",
"state": "California",
"pop": "3976322"
}
},
{
"city": {
"name": "Chicago",
"state": "Illinois",
"pop": "2704958"
}
}
]
}

This array of data doesn't translate well to a string-to-string map. In such a case, you can transform
an object to a simple string so that you can send it to your bot with the PostContent (p. 327) and
PostText (p. 335) operations.

For example, if you are using JavaScript, you can use the JSON.stringify operation to convert an
object to JSON, and the JSON.parse operation to convert JSON text to a JavaScript object:

// To convert an object to a string.


var jsonString = JSON.stringify(object, null, 2);
// To convert a string to an object.
var obj = JSON.parse(JSON string);

23
Amazon Lex Developer Guide
Deployment Options

To send session attributes with the PostContent operation, you must base64 encode the attributes
before you add them to the request header, as shown in the following JavaScript code:

var encodedAttributes = new Buffer(attributeString).toString("base64");

You can send binary data to the PostContent and PostText operations by first converting the data to
a base64-encoded string, and then sending the string as the value in the session attributes:

"sessionAttributes" : {
"binaryData": "base64 encoded data"
}

Bot Deployment Options


Currently, Amazon Lex provides the following bot deployment options:

• AWS Mobile SDK – You can build mobile applications that communicate with Amazon Lex using the
AWS Mobile SDKs.
• Facebook Messenger – You can integrate your Facebook Messenger page with your Amazon Lex bot
so that end users on Facebook can communicate with the bot. In the current implementation, this
integration supports only text input messages.
• Slack – You can integrate your Amazon Lex bot with a Slack messaging application.
• Twilio – You can integrate your Amazon Lex bot with the Twilio Simple Messaging Service (SMS).

For examples, see Deploying Amazon Lex Bots (p. 109).

Built-in Intents and Slot Types


To make it easier to create your bots, Amazon Lex allows you to use standard Alexa built-in intents and
slot types.

Topics
• Built-in Intents (p. 24)
• Built-in Slot Types (p. 25)

Built-in Intents
For common actions, you can use the Alexa standard built-in intents library. To create an intent from
a built-in intent, choose a built-intent in the console, and give it a new name. The new intent has the
configuration of base intent, such as the sample utterances and slots.

For a list of built-in intents, see Standard Built-in Intents in the Alexa Skills Kit.
Note
Amazon Lex doesn't support the following intents:

• AMAZON.YesIntent
• AMAZON.NoIntent
• The intents in the Built-in Intent Library in the Alexa Skills Kit

24
Amazon Lex Developer Guide
Built-in Slot Types

In the current implementation, you can't do the following:

• Add or remove sample utterances or slots from the base intent


• Configure slots for built-in intents

Built-in Slot Types


Amazon Lex supports built-in slot types from the Alexa Skills Kit. You can create slots of these types in
your intents. This eliminates the need to create enumeration values for commonly used slot data such as
date, time, and location. Built-in slot types do not have versions.

For a list of available built-in slot types, see Slot Type Reference in the Alexa Skills Kit documentation.
Note
Amazon Lex doesn't support the AMAZON.LITERAL built-in slot type.

Amazon Lex supports the following built-in slot types. Slot types marked "Developer Preview" are in
preview and might change.

Slot Type Short Description Supported Languages Availability

AMAZON.EmailAddress (p.Converts
26) words that English (US) Developer Preview
represent an email
address into a standard
email address

AMAZON.Percentage (p. 26)


Converts words that English (US) Developer Preview
represent a percentage
to a number and a
percent sign (%)

AMAZON.PhoneNumber (p.Converts
27) words that English (US) Developer Preview
represent a phone
number into a numeric
string

AMAZON.SpeedUnit (p. 27)Converts words that English (US) Developer Preview


represent a speed
unit into a standard
abbreviation

AMAZON.WeightUnit (p. 28)


Converts words that English (US) Developer Preview
represent a weight
unit into a standard
abbreviation

When used with Amazon Lex, the following slot types extend the Alexa Skill Kit slot type.

Slot Type Short Description Supported Languages Availability

AMAZON.NUMBER (p. 26) Converts numeric words English (US) Developer Preview
into digits

AMAZON.TIME (p. 28) Converts words that English (US) Available


indicate times into a
time format

25
Amazon Lex Developer Guide
Built-in Slot Types

The built-in slot types are described in detail in the following sections.

Alexa Skills Kit Slot Types


You can use any of the slot types from the Alexa Skills Kit in your Amazon Lex bots. To use one of the slot
types, specify the slot type name in the console or in a call to the the section called “PutIntent” (p. 309)
operation. For a list of available built-in slot types, see Slot Type Reference in the Alexa Skills Kit.
Note
Amazon Lex doesn't support the AMAZON.LITERAL built-in slot type.

AMAZON.EmailAddress

This slot type is in preview release for Amazon Lex and is subject to change.

Recognizes words that represent an email address provided as username@domain. Addresses can include
the following special characters in a user name: underscore (_), hyphen (-), period (.), and the plus sign
(+).

AMAZON.NUMBER

This slot type is in preview release for Amazon Lex and is subject to change.

Converts numeric words into digits.

Amazon Lex extends the AMAZON.NUMBER slot type to convert words or numbers that express a
number into digits, including decimal numbers. The following table shows how the AMAZON.NUMBER slot
type captures numeric words.

Input Response

one hundred twenty three point four five 123.45

one hundred twenty three dot four five 123.45

point four two 0.42

point forty two 0.42

232.998 232.998

50 50

AMAZON.Percentage

This slot type is in preview release for Amazon Lex and is subject to change.

Converts words and symbols that represent a percentage into a numeric value with a percent sign (%).

If the user enters a number without a percent sign or the word "percent," the slot value is set to the
number. The following table shows how the AMAZON.Percentage slot type captures percentages.

26
Amazon Lex Developer Guide
Built-in Slot Types

Input Response

50 percent 50%

0.4percent 0.4%

23.5% 23.5%

25 25

AMAZON.PhoneNumber

This slot type is in preview release for Amazon Lex and is subject to change.

Converts the numbers or words that represent a phone number into a string format without punctuation
as follows.
Note
Only U.S. phone numbers are supported.

Type Description Input Result

International number 11-digit number with +1 509 555-1212 +15095551212


with leading plus (+) leading plus sign.
sign

International number 11-digit number 1 (509) 555-1212 15095551212


without leading plus (+) without leading plus
sign sign

National number 10-digit number (509) 555-1212 5095551212


without international
code

Local number 7-digit phone 555-1212 5551212


number without an
international code or an
area code

AMAZON.SpeedUnit

This slot type is in preview release for Amazon Lex and is subject to change.

Converts words that represent speed units into the corresponding abbreviation.

For example, "miles per hour" is converted to mph.

The following examples show how the AMAZON.SpeedUnit slot type captures speed units.

27
Amazon Lex Developer Guide
Built-in Slot Types

Speed unit Abbreviation

miles per hour, mph, MPH, m/h mph

kilometers per hour, km per hour, kmph, KMPH, kmph


km/h

meters per second, mps, MPS, m/s mps

nautical miles per hour, knots, knot knot

AMAZON.TIME
Converts words that represent times into time values.

Amazon Lex extends the AMAZON.TIME slot type to include resolutions for ambiguous times. When a
user enters an ambiguous time, Amazon Lex uses the slotDetails attribute of a Lambda event to pass
resolutions for the ambiguous times to your Lambda function. For example, if your bot prompts the user
for a delivery time, the user can respond by saying "10 o'clock." This time is ambiguous. It means either
10:00 AM or 10:00 PM. In this case, the value in the slots map is null, and the slotDetails entity
contains the two possible resolutions of the time. Amazon Lex inputs the following into the Lambda
function:

"slots": {
"deliveryTime": null
},
"slotDetails": {
"deliveryTime": {
"resolutions": [
{
"value": "10:00"
},
{
"value": "22:00"
}
]
}
}

When the user responds with an unambiguous time, Amazon Lex sends the time to your Lambda
function in the slots attribute of the Lambda event and the slotDetails attribute is empty. For
example, if your user responds to the prompt for a delivery time with "10:00 PM," Amazon Lex inputs the
following into the Lambda function:

"slots": {
"deliveryTime": "22:00"
}

For more information about the data sent from Amazon Lex to a Lambda function, see Input Event
Format (p. 101).

AMAZON.WeightUnit

This slot type is in preview release for Amazon Lex and is subject to change.

28
Amazon Lex Developer Guide
Custom Slot Types

Converts words that represent a weight unit into the corresponding abbreviation. For example,
"kilogram" is converted to kg.

The following examples show how the AMAZON.WeightUnit slot type captures weight units:

Weight unit Abbreviation

kilograms, kilos, kgs, KGS kg

grams, gms, gm, GMS, g g

milligrams, mg, mgs mg

pounds, lbs, LBS lbs

ounces, oz, OZ oz

tonne, ton, t t

kiloton, kt kt

Custom Slot Types


For each intent, you can specify parameters that indicate the information that the intent needs to fulfill
the user's request. These parameters, or slots, have a type. A slot type is a list of values that Amazon Lex
uses to train the machine learning model to recognize values for a slot. For example, you can define a
slot type called "Genres." Each value in the slot type is the name of a genre, "comedy," "adventure,"
"documentary," etc. You can define a synonym for a slot type value. For example, you can define the
synonyms "funny" and "humorous" for the value "comedy."

You can configure the slot type to restrict resolution to the slot values. The slot values will be used as an
enumeration and the value entered by the user will be resolved to the slot value only if it is the same as
one of the slot values or a synonym. A synonym is resolved to the corresponding slot value. For example,
if the user enters "funny" it will resolve to the slot value "comedy."

Alternately, you can configure the slot type to expand the values. Slot values will be used as training data
and the slot is resolved to the value provided by the user if it is similar to the slot values and synonyms.
This is the default behavior.

Amazon Lex maintains a list of possible resolutions for a slot. Each entry in the list provides a resolution
value that Amazon Lex recognized as additional possibilities for the slot. A resolution value is the best
effort to match the slot value. The list contains up to five values.

When the value entered by the user is a synonym, the first entry in the list of resolution values is the slot
type value. For example, if the user enters "funny," the slots field contains "funny" and the first entry in
the slotDetails field is "comedy." You can configure the valueSelectionStrategy when you create
or update a slot type with the PutSlotType (p. 319) operation so that the slot value is filled with the
first value in the resolution list.

If you are using a Lambda function, the input event to the function includes a resolution list called
slotDetails. The following example shows the slot and slot details section of the input to a Lambda
function:

"slots": {
"MovieGenre": "funny";
},

29
Amazon Lex Developer Guide
Custom Slot Types

"slotDetails": {
"Movie": {
"resolutions": [
"value": "comedy"
]
}
}

For each slot type, you can define a maximum of 10,000 values and synonyms. Each bot can have a total
number of 50,000 slot type values and synonyms.

30
Amazon Lex Developer Guide
Step 1: Set Up an Account

Getting Started with Amazon Lex


Amazon Lex provides API operations that you can integrate with your existing applications. For a list of
supported operations, see the API Reference (p. 202). You can use any of the following options:

• AWS SDK — When using the SDKs your requests to Amazon Lex are automatically signed and
authenticated using the credentials that you provide. This is the recommended choice for building your
applications.
• AWS CLI — You can use the AWS CLI to access any Amazon Lex feature without having to write any
code.
• AWS Console — The console is the easiest way to get started testing and using Amazon Lex

If you are new to Amazon Lex, we recommend that you read Amazon Lex: How It Works (p. 3). first.

Topics
• Step 1: Set Up an AWS Account and Create an Administrator User (p. 31)
• Step 2: Set Up the AWS Command Line Interface (p. 32)
• Step 3: Getting Started (Console) (p. 33)
• Step 4: Getting Started (AWS CLI) (p. 72)

Step 1: Set Up an AWS Account and Create an


Administrator User
Before you use Amazon Lex for the first time, complete the following tasks:

1. Sign Up for AWS (p. 31)


2. Create an IAM User (p. 32)

Sign Up for AWS


If you already have an AWS account, skip this task.

When you sign up for Amazon Web Services (AWS), your AWS account is automatically signed up for all
services in AWS, including Amazon Lex. You are charged only for the services that you use.

With Amazon Lex, you pay only for the resources that you use. If you are a new AWS customer, you can
get started with Amazon Lex for free. For more information, see AWS Free Usage Tier.

If you already have an AWS account, skip to the next task. If you don't have an AWS account, use the
following procedure to create one.

To create an AWS account

1. Open https://aws.amazon.com/, and then choose Create an AWS Account.


Note
If you previously signed in to the AWS Management Console using AWS account root user
credentials, choose Sign in to a different account. If you previously signed in to the console
using IAM credentials, choose Sign-in using root account credentials. Then choose Create
a new AWS account.

31
Amazon Lex Developer Guide
Create an IAM User

2. Follow the online instructions.

Part of the sign-up procedure involves receiving a phone call and entering a verification code using
the phone keypad.

Write down your AWS account ID because you'll need it for the next task.

Create an IAM User


Services in AWS, such as Amazon Lex, require that you provide credentials when you access them so that
the service can determine whether you have permissions to access the resources owned by that service.
The console requires your password. You can create access keys for your AWS account to access the AWS
CLI or API.

However, we don't recommend that you access AWS using the credentials for your AWS account. Instead,
we recommend that you:

• Use AWS Identity and Access Management (IAM) to create an IAM user
• Add the user to an IAM group with administrative permissions
• Grant administrative permissions to the IAM user that you created.

You can then access AWS using a special URL and the IAM user's credentials.

The Getting Started exercises in this guide assume that you have a user (adminuser) with administrator
privileges. Follow the procedure to create adminuser in your account.

To create an administrator user and sign in to the console

1. Create an administrator user called adminuser in your AWS account. For instructions, see Creating
Your First IAM User and Administrators Group in the IAM User Guide.
2. As a user, you can sign in to the AWS Management Console using a special URL. For more
information, How Users Sign In to Your Account in the IAM User Guide.

For more information about IAM, see the following:

• AWS Identity and Access Management (IAM)


• Getting Started
• IAM User Guide

Next Step
Step 2: Set Up the AWS Command Line Interface (p. 32)

Step 2: Set Up the AWS Command Line Interface


If you prefer to use Amazon Lex with the AWS Command Line Interface (AWS CLI), download and
configure it.
Important
You don't need the AWS CLI to perform the steps in the Getting Started exercises. However,
some of the later exercises in this guide use the AWS CLI. If you prefer to start by using the
console, skip this step and go to Step 3: Getting Started (Console) (p. 33). Later, when you
need the AWS CLI, return here to set it up.

32
Amazon Lex Developer Guide

To set up the AWS CLI

1. Download and configure the AWS CLI. For instructions, see the following topics in the AWS
Command Line Interface User Guide:

• Getting Set Up with the AWS Command Line Interface


• Configuring the AWS Command Line Interface
2. Add a named profile for the administrator user to the end of the AWS CLI config file. You use this
profile when executing AWS CLI commands. For more information about named profiles, see Named
Profiles in the AWS Command Line Interface User Guide.

[profile adminuser]
aws_access_key_id = adminuser access key ID
aws_secret_access_key = adminuser secret access key
region = aws-region

For a list of available AWS Regions, see Regions and Endpoints in the Amazon Web Services General
Reference.
3. Verify the setup by typing the Help command at the command prompt:

aws help

Step 3: Getting Started (Console) (p. 33)

Step 3: Getting Started (Console)


The easiest way to learn how to use Amazon Lex is by using the console. To get you started, we created
the following exercises, all of which use the console:

• Exercise 1 — Create an Amazon Lex bot using a blueprint, a predefined bot that provides all of the
necessary bot configuration. You do only a minimum of work to test the end-to-end setup.

In addition, you use the Lambda function blueprint, provided by AWS Lambda, to create a Lambda
function. The function is a code hook that uses predefined code that is compatible with your bot.
• Exercise 2 — Create a custom bot by manually creating and configuring a bot. You also create a
Lambda function as a code hook. Sample code is provided.
• Exercise 3 — Publish a bot, and then create a new version of it. As part of this exercise you create an
alias that points to the bot version.

Topics
• Exercise 1: Create an Amazon Lex Bot Using a Blueprint (Console) (p. 33)
• Exercise 2: Create a Custom Amazon Lex Bot (p. 60)
• Exercise 3: Publish a Version and Create an Alias (p. 71)

Exercise 1: Create an Amazon Lex Bot Using a


Blueprint (Console)
In this exercise, you do the following:

33
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

• Create your first Amazon Lex bot, and test it in the Amazon Lex console.

For this exercise, you use the OrderFlowers blueprint. For information about blueprints, see Amazon
Lex and AWS Lambda Blueprints (p. 108).

 
• Create an AWS Lambda function and test it in the Lambda console. While processing a request, your
bot calls this Lambda function. For this exercise, you use a Lambda blueprint (lex-order-flowers-
python) provided in the AWS Lambda console to create your Lambda function. The blueprint code
illustrates how you can use the same Lambda function to perform initialization and validation, and to
fulfill the OrderFlowers intent.

 
• Update the bot to add the Lambda function as the code hook to fulfill the intent. Test the end-to-end
experience.

The following sections explain what the blueprints do.

Amazon Lex Bot: Blueprint Overview


You use the OrderFlowers blueprint to create an Amazon Lex bot.For more information about the
structure of a bot, see Amazon Lex: How It Works (p. 3). The bot is preconfigured as follows:

• Intent – OrderFlowers
• Slot types – One custom slot type called FlowerTypes with enumeration values: roses, lilies, and
tulips.
• Slots – The intent requires the following information (that is, slots) before the bot can fulfill the intent.
• PickupTime (AMAZON.TIME built-in type)
• FlowerType (FlowerTypes custom type)
• PickupDate (AMAZON.DATE built-in type)
• Utterance – The following sample utterances indicate the user's intent:
• "I would like to pick up flowers."
• "I would like to order some flowers."
• Prompts – After the bot identifies the intent, it uses the following prompts to fill the slots:
• Prompt for the FlowerType slot – "What type of flowers would you like to order?"
• Prompt for the PickupDate slot – "What day do you want the {FlowerType} to be picked up?"
• Prompt for the PickupTime slot – "At what time do you want the {FlowerType} to be picked up?"
• Confirmation statement – "Okay, your {FlowerType} will be ready for pickup by {PickupTime} on
{PickupDate}. Does this sound okay?"

AWS Lambda Function: Blueprint Summary


The Lambda function in this exercise performs both initialization and validation and fulfillment tasks.
Therefore, after creating the Lambda function, you update the intent configuration by specifying the
same Lambda function as a code hook to handle both the initialization and validation and fulfillment
tasks.

• As an initialization and validation code hook, the Lambda function performs basic validation. For
example, if the user provides a time for pickup that is outside of normal business hours, the Lambda
function directs Amazon Lex to re-prompt the user for the time.
• As part of the fulfillment code hook, the Lambda function returns a summary message indicating that
the flower order has been placed (that is, the intent is fulfilled).

34
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

Next Step

Step 1: Create an Amazon Lex Bot (Console) (p. 35)

Step 1: Create an Amazon Lex Bot (Console)


For this exercise, create a bot for ordering flowers, called OrderFlowersBot.

To create an Amazon Lex bot (console)

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. If this is your first bot, choose Get Started; otherwise, on the Bots page, choose Create.
3. On the Create your Lex bot page, provide the following information, and then choose Create.

• Choose the OrderFlowers blueprint.


• Leave the default bot name (OrderFlowers).
• For COPPA, choose No.
4. Choose Create. The console makes the necessary requests to Amazon Lex to save the configuration.
The console then displays the bot editor window.
5. Wait for confirmation that your bot was built.
6. Test the bot.
Note
You can test the bot by typing text into the test window, or, for compatible browsers, by
choosing the microphone button in the test window and speaking.

Use the following example text to engage in conversation with the bot to order flowers:

35
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

From this input, the bot infers the OrderFlowers intent and prompts for slot data. When you
provide all of the required slot data, the bot fulfills the intent (OrderFlowers) by returning all
of the information to the client application (in this case, the console). The console shows the
information in the test window.

Specifically:

• In the statement "What day do you want the roses to be picked up?,"the term "roses" appears
because the prompt for the pickupDate slot is configured using substitutions, {FlowerType}.
Verify this in the console.
• The "Okay, your roses will be ready..." statement is the confirmation prompt that you configured.
• The last statement ("FlowerType:roses...") is just the slot data that is returned to the client,
in this case, in the test window. In the next exercise, you use a Lambda function to fulfill the
intent, in which case you get a message indicating that the order is fulfilled.

Next Step

Step 2 (Optional): Review the Details of Information Flow (Console) (p. 37)

36
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

Step 2 (Optional): Review the Details of Information Flow


(Console)
This section explains the flow of information between a client and Amazon Lex for each user input in our
example conversation.

To see the flow of information for spoken or typed content, choose the appropriate topic.

Topics
• Step 2a (Optional): Review the Details of the Spoken Information Flow (Console) (p. 37)
• Step 2b (Optional): Review the Details of the Typed Information Flow (Console) (p. 41)

Step 2a (Optional): Review the Details of the Spoken Information Flow (Console)
This section explains the flow of information between the client and Amazon Lex when the client uses
speech to send requests. For more information, see PostContent (p. 327).

1. The user says: I would like to order some flowers.

a. The client (console) sends the following PostContent (p. 327) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content
HTTP/1.1
x-amz-lex-session-attributes: "e30="
Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1"
Accept: "audio/mpeg"

Request body
input stream

Both the request URI and the body provide information to Amazon Lex:

• Request URI – Provides the bot name (OrderFlowers), bot alias ($LATEST), and the
user name (a random string that identifies the user). content indicates that this is a
PostContent API request (not a PostText request).
• Request headers
• x-amz-lex-session-attributes – The base64-encoded value represents "{}". When the
client makes the first request, there are no session attributes.
• Content-Type – Reflects the audio format.
• Request body – The user input audio stream ("I would like to order some flowers.").

Note
If the user chooses to send text ("I would like to order some flowers") to the
PostContent API instead of speaking, the request body is the user input. The
Content-Type header is set accordingly:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/
content HTTP/1.1
x-amz-lex-session-attributes: "e30="
Content-Type: "text/plain; charset=utf-8"
Accept: accept

Request body
input stream

37
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

b. From the input stream, Amazon Lex detects the intent (OrderFlowers). It then chooses one
of the intent's slots (in this case, the FlowerType) and one of its value elicitation prompts, and
then sends a response with the following headers:

x-amz-lex-dialog-state:ElicitSlot
x-amz-lex-input-transcript:I would like to order some flowers.
x-amz-lex-intent-name:OrderFlowers
x-amz-lex-message:What type of flowers would you like to order?
x-amz-lex-session-attributes:e30=
x-amz-lex-slot-to-elicit:FlowerType
x-amz-lex-
slots:eyJQaWNrdXBUaW1lIjpudWxsLCJGbG93ZXJUeXBlIjpudWxsLCJQaWNrdXBEYXRlIjpudWxsfQ==

The header values provide the following information:

• x-amz-lex-input-transcript – Provides the transcript of the audio (user input) from the
request
• x-amz-lex-message – Provides the transcript of the audio Amazon Lex returned in the
response
• x-amz-lex-slots – The base64 encoded version of the slots and values:

{"PickupTime":null,"FlowerType":null,"PickupDate":null}

• x-amz-lex-session-attributes – The base64-encoded version of the session attributes


({})

The client plays the audio in the response body.


2. The user says: roses

a. The client (console) sends the following PostContent (p. 327) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content
HTTP/1.1
x-amz-lex-session-attributes: "e30="
Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1"
Accept: "audio/mpeg"

Request body
input stream ("roses")

The request body is the user input audio stream (roses). The sessionAttributes remains
empty.
b. Amazon Lex interprets the input stream in the context of the current intent (it remembers
that it had asked this user for information pertaining to the FlowerType slot). Amazon Lex
first updates the slot value for the current intent. It then chooses another slot (PickupDate),
along with one of its prompt messages (When do you want to pick up the roses?), and returns a
response with the following headers:

x-amz-lex-dialog-state:ElicitSlot
x-amz-lex-input-transcript:roses
x-amz-lex-intent-name:OrderFlowers
x-amz-lex-message:When do you want to pick up the roses?
x-amz-lex-session-attributes:e30=
x-amz-lex-slot-to-elicit:PickupDate

38
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

x-amz-lex-
slots:eyJQaWNrdXBUaW1lIjpudWxsLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6bnVsbH0=

The header values provide the following information:

• x-amz-lex-slots – The base64-encoded version of the slots and values:

{"PickupTime":null,"FlowerType":"roses","PickupDate":null}

• x-amz-lex-session-attributes – The base64-encoded version of the session attributes


({})

The client plays the audio in the response body.


3. The user says: tomorrow

a. The client (console) sends the following PostContent (p. 327) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content
HTTP/1.1
x-amz-lex-session-attributes: "e30="
Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1"
Accept: "audio/mpeg"

Request body
input stream ("tomorrow")

The request body is the user input audio stream ("tomorrow").The sessionAttributes
remains empty.
b. Amazon Lex interprets the input stream in the context of the current intent (it remembers that
it had asked this user for information pertaining to the PickupDate slot). Amazon Lex updates
the slot (PickupDate) value for the current intent. It then chooses another slot to elicit value
for (PickupTime) and one of the value elicitation prompts (When do you want to pick up the
roses on 2017-03-18?), and returns a response with the following headers:

x-amz-lex-dialog-state:ElicitSlot
x-amz-lex-input-transcript:tomorrow
x-amz-lex-intent-name:OrderFlowers
x-amz-lex-message:When do you want to pick up the roses on 2017-03-18?
x-amz-lex-session-attributes:e30=
x-amz-lex-slot-to-elicit:PickupTime
x-amz-lex-
slots:eyJQaWNrdXBUaW1lIjpudWxsLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6IjIwMTctMDMtMTgif
x-amzn-RequestId:3a205b70-0b69-11e7-b447-eb69face3e6f

The header values provide the following information:

• x-amz-lex-slots – The base64-encoded version of the slots and values:

{"PickupTime":null,"FlowerType":"roses","PickupDate":"2017-03-18"}

• x-amz-lex-session-attributes – The base64-encoded version of the session attributes


({})

The client plays the audio in the response body.


4. The user says: 6 pm

39
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

a. The client (console) sends the following PostContent (p. 327) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content
HTTP/1.1
x-amz-lex-session-attributes: "e30="
Content-Type: "text/plain; charset=utf-8"
Accept: "audio/mpeg"

Request body
input stream ("6 pm")

The request body is the user input audio stream ("6 pm"). The sessionAttributes remains
empty.
b. Amazon Lex interprets the input stream in the context of the current intent (it remembers that
it had asked this user for information pertaining to the PickupTime slot). It first updates the
slot value for the current intent.

Now Amazon Lex detects that it has information for all of the slots. However, the
OrderFlowers intent is configured with a confirmation message. Therefore, Amazon Lex
needs an explicit confirmation from the user before it can proceed to fulfill the intent. It sends a
response with the following headers requesting confirmation before ordering the flowers:

x-amz-lex-dialog-state:ConfirmIntent
x-amz-lex-input-transcript:six p. m.
x-amz-lex-intent-name:OrderFlowers
x-amz-lex-message:Okay, your roses will be ready for pickup by 18:00 on 2017-03-18.
Does this sound okay?
x-amz-lex-session-attributes:e30=
x-amz-lex-
slots:eyJQaWNrdXBUaW1lIjoiMTg6MDAiLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6IjIwMTctMDMtM
x-amzn-RequestId:083ca360-0b6a-11e7-b447-eb69face3e6f

The header values provide the following information:

• x-amz-lex-slots – The base64-encoded version of the slots and values:

{"PickupTime":"18:00","FlowerType":"roses","PickupDate":"2017-03-18"}

• x-amz-lex-session-attributes – The base64-encoded version of the session attributes


({})

The client plays the audio in the response body.


5. The user says: Yes

a. The client (console) sends the following PostContent (p. 327) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content
HTTP/1.1
x-amz-lex-session-attributes: "e30="
Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1"
Accept: "audio/mpeg"

Request body
input stream ("Yes")

40
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

The request body is the user input audio stream ("Yes"). The sessionAttributes remains
empty.
b. Amazon Lex interprets the input stream and understands that the user want to proceed with the
order. The OrderFlowers intent is configured with ReturnIntent as the fulfillment activity.
This directs Amazon Lex to return all of the intent data to the client. Amazon Lex returns a
response with following:

x-amz-lex-dialog-state:ReadyForFulfillment
x-amz-lex-input-transcript:yes
x-amz-lex-intent-name:OrderFlowers
x-amz-lex-session-attributes:e30=
x-amz-lex-
slots:eyJQaWNrdXBUaW1lIjoiMTg6MDAiLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6IjIwMTctMDMtM

Thex-amz-lex-dialog-state response header is set to ReadyForFulfillment. The client


can then fulfill the intent.
6. Now, retest the bot. To establish a new (user) context, choose the Clear link in the console. Provide
data for the OrderFlowers intent, and include some invalid data. For example:

• Jasmine as the flower type (it is not one of the supported flower types)
• Yesterday as the day when you want to pick up the flowers

Notice that the bot accepts these values because you don't have any code to initialize and validate
the user data. In the next section, you add a Lambda function to do this. Note the following about
the Lambda function:

• It validates slot data after every user input. It fulfills the intent at the end. That is, the bot
processes the flower order and returns a message to the user instead of simply returning slot data
to the client. For more information, see Using Lambda Functions (p. 101).
• It also sets the session attributes. For more information about session attributes, see
PostText (p. 335).

After you complete the Getting Started section, you can do the additional exercises (Additional
Examples: Creating Amazon Lex Bots (p. 130) ). Example Bot: BookTrip (p. 148) uses session
attributes to share cross-intent information to engage in a dynamic conversation with the user.

Next Step

Step 3: Create a Lambda Function (Console) (p. 45)

Step 2b (Optional): Review the Details of the Typed Information Flow (Console)
This section explains flow of information between client and Amazon Lex in which the client uses the
PostText API to send requests. For more information, see PostText (p. 335).

1. User types: I would like to order some flowers

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "I would like to order some flowers",
"sessionAttributes": {}

41
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

Both the request URI and the body provide information to Amazon Lex:

• Request URI – Provides bot name (OrderFlowers), bot alias ($LATEST), and user name (a
random string identifying the user). The trailing text indicates that it is a PostText API
request (and not PostContent).

 
• Request body – Includes the user input (inputText) and empty sessionAttributes.
When the client makes the first request, there are no session attributes. The Lambda function
initiates them later.
b. From the inputText, Amazon Lex detects the intent (OrderFlowers). This intent does not
have any code hooks (that is, the Lambda functions) for initialization and validation of user
input or fulfillment.

Amazon Lex chooses one of the intent's slots (FlowerType) to elicit the value. It also selects
one of the value-elicitation prompts for the slot (all part of the intent configuration), and
then sends the following response back to the client. The console displays the message in the
response to the user.

The client displays the message in the response.


2. User types: roses

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "roses",
"sessionAttributes": {}
}

The inputText in the request body provides user input. The sessionAttributes remains
empty.
b. Amazon Lex first interprets the inputText in the context of the current intent—the service
remembers that it had asked the specific user for information about the FlowerType slot.
Amazon Lex first updates the slot value for the current intent and chooses another slot

42
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

(PickupDate) along with one of its prompt messages—What day do you want the roses to be
picked up?— for the slot.

Then, Amazon Lex returns the following response:

The client displays the message in the response.


3. User types: tomorrow

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "tomorrow",
"sessionAttributes": {}
}

The inputText in the request body provides user input. The sessionAttributes remains
empty.
b. Amazon Lex first interprets the inputText in the context of the current intent—the service
remembers that it had asked the specific user for information about the PickupDate slot.
Amazon Lex updates the slot (PickupDate) value for the current intent. It chooses another slot
to elicit value for (PickupTime). It returns one of the value-elicitation prompts—Deliver the
roses at what time on 2017-01-01?—to the client.

Amazon Lex then returns the following response:

43
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

The client displays the message in the response.


4. User types: 6 pm

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "6 pm",
"sessionAttributes": {}
}

The inputText in the request body provides user input. The sessionAttributes remains
empty.
b. Amazon Lex first interprets the inputText in the context of the current intent—the service
remembers that it had asked the specific user for information about the PickupTime slot.
Amazon Lex first updates the slot value for the current intent. Now Amazon Lex detects that it
has information for all the slots.

The OrderFlowers intent is configured with a confirmation message. Therefore, Amazon Lex
needs an explicit confirmation from the user before it can proceed to fulfill the intent. Amazon
Lex sends the following message to the client requesting confirmation before ordering the
flowers:

The client displays the message in the response.


5. User types: Yes

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "Yes",
"sessionAttributes": {}
}

The inputText in the request body provides user input. The sessionAttributes remains
empty.

44
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

b. Amazon Lex interprets the inputText in the context of confirming the current intent. It
understands that the user want to proceed with the order. The OrderFlowers intent is
configured with ReturnIntent as the fulfillment activity (there is no Lambda function to fulfill
the intent). Therefore, Amazon Lex returns the slot data to the client.

Amazon Lex set the dialogState to ReadyForFulfillment. The client can then fulfill the
intent.
6. Now test the bot again. To do that, you must choose the Clear link in the console to establish a new
(user) context. Now as you provide data for the order flowers intent, try to provide invalid data. For
example:

• Jasmine as the flower type (it is not one of the supported flower types).
• Yesterday as the day when you want to pick up the flowers.

Notice that the bot accepts these values because you don't have any code to initialize/validate
user data. In the next section, you add a Lambda function to do this. Note the following about the
Lambda function:

• The Lambda function validates slot data after every user input. It fulfills the intent at the end.
That is, the bot processes the flowers order and returns a message to the user instead of simply
returning slot data to the client. For more information, see Using Lambda Functions (p. 101).
• The Lambda function also sets the session attributes. For more information about session
attributes, see PostText (p. 335).

After you complete the Getting Started section, you can do the additional exercises (Additional
Examples: Creating Amazon Lex Bots (p. 130) ). Example Bot: BookTrip (p. 148) uses session
attributes to share cross-intent information to engage in a dynamic conversation with the user.

Next Step

Step 3: Create a Lambda Function (Console) (p. 45)

Step 3: Create a Lambda Function (Console)


Create a Lambda function (using the lex-order-flowers-python blueprint) and perform test invocation
using sample event data in the AWS Lambda console.

You return to the Amazon Lex console and add the Lambda function as the code hook to fulfill the
OrderFlowers intent in the OrderFlowersBot that you created in the preceding section.

45
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

To create the Lambda function (console)

1. Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2. Choose Create function.
3. On the Create function page, choose Blueprints. Type lex- in the filter text box to find the
blueprint, choose the lex-order-flowers-python blueprint.

Lambda function blueprints are provided in both Node.js and Python. For this exercise, use the
Python-based blueprint.
4. On the Basic information page, do the following, and then choose Create function.

• Type a Lambda function name (OrderFlowersCodeHook).


• For the IAM role, choose Create a new role from template(s).
• Type a role name (LexOrderFlowersRole).
• Leave the other default values.
5. Choose Create function.
6. Test the Lambda function.

a. Choose Select a test events, Configure test event.


b. Choose Lex-Order Flowers from the Event template list. This sample event matches the
Amazon Lex request/response model (see Using Lambda Functions (p. 101)). Give the test
event a name (LexOrderFlowersTest).
c. Choose Create.
d. Verify that the Lambda function successfully executed. The response in this case matches the
Amazon Lex response model.

Next Step

Step 4: Add the Lambda Function as Code Hook (Console) (p. 46)

Step 4: Add the Lambda Function as Code Hook (Console)


In this section, you update the configuration of the OrderFlowers intent to use the Lambda function as
follows:

• First use the Lambda function as a code hook to perform fulfillment of the OrderFlowers intent. You
test the bot and verify that you received a fulfillment message from the Lambda function. Amazon Lex
invokes the Lambda function only after you provide data for all the required slots for ordering flowers.
• Configure the same Lambda function as a code hook to perform initialization and validation. You test
and verify that the Lambda function performs validation (as you provide slot data).

To add a Lambda function as a code hook (console)

1. In the Amazon Lex console, select the OrderFlowers bot. The console shows the OrderFlowers
intent. Make sure that the intent version is set to $LATEST because this is the only version that we
can modify.
2. Add the Lambda function as the fulfillment code hook and test it.

a. In the Editor, choose AWS Lambda function as Fulfillment, and select the Lambda function
that you created in the preceding step (OrderFlowersCodeHook). Choose OK to give Amazon
Lex permission to invoke the Lambda function.

46
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

You are configuring this Lambda function as a code hook to fulfill the intent. Amazon Lex
invokes this function only after it has all the necessary slot data from the user to fulfill the
intent.
b. Specify a Goodbye message.
c. Choose Build.
d. Test the bot using the previous conversation.

The last statement "Thanks, your order for roses....." is a response from the Lambda function that
you configured as a code hook. In the preceding section, there was no Lambda function. Now you are
using a Lambda function to actually fulfill the OrderFlowers intent.
3. Add the Lambda function as an initialization and validation code hook, and test.

The sample Lambda function code that you are using can both perform user input validation and
fulfillment. The input event the Lambda function receives has a field (invocationSource) that
the code uses to determine what portion of the code to execute. For more information, see Lambda
Function Input Event and Response Format (p. 101).

a. Select the $LATEST version of the OrderFlowers intent. That's is the only version that you can
update.
b. In the Editor, choose Initialization and validation in Options.
c. Again, select the same Lambda function.
d. Choose Build.
e. Test the bot.

You are now ready to converse with Amazon Lex as follows. To test the validation portion,
choose time 6 PM, and your Lambda function returns a response ("Our business hours are from
10 AM to 5 PM."), and prompts you again. After you provide all the valid slot data, the Lambda
function fulfills the order.

47
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

Next Step

Step 5 (Optional): Review the Details of the Information Flow (Console) (p. 48)

Step 5 (Optional): Review the Details of the Information Flow


(Console)
This section explains the flow of information between the client and Amazon Lex for each user input,
including the integration of the Lambda function.
Note
The section assumes that the client sends requests to Amazon Lex using the PostText runtime
API and shows request and response details accordingly. For an example of the information flow
between the client and Amazon Lex in which client uses the PostContent API, see Step 2a
(Optional): Review the Details of the Spoken Information Flow (Console) (p. 37).

48
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

For more information about the PostText runtime API and additional details on the requests and
responses shown in the following steps, see PostText (p. 335).

1. User: I would like to order some flowers.

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "I would like to order some flowers",
"sessionAttributes": {}
}

Both the request URI and the body provide information to Amazon Lex:

• Request URI – Provides bot name (OrderFlowers), bot alias ($LATEST), and user name (a
random string identifying the user). The trailing text indicates that it is a PostText API
request (and not PostContent).
• Request body – Includes the user input (inputText) and empty sessionAttributes.
When the client makes the first request, there are no session attributes. The Lambda function
initiates them later.
b. From the inputText, Amazon Lex detects the intent (OrderFlowers). This intent is configured
with a Lambda function as a code hook for user data initialization and validation. Therefore,
Amazon Lex invokes that Lambda function by passing the following information as event data:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "ignw84y6seypre4xly5rimopuri2xwnd",
"sessionAttributes": {},
"bot": {
"name": "OrderFlowers",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "OrderFlowers",
"slots": {
"PickupTime": null,
"FlowerType": null,
"PickupDate": null
},
"confirmationStatus": "None"
}
}

For more information, see Input Event Format (p. 101).

In addition to the information that the client sent, Amazon Lex also includes the following
additional data:

• messageVersion – Currently Amazon Lex supports only the 1.0 version.


• invocationSource – Indicates the purpose of Lambda function invocation. In this case, it
is to perform user data initialization and validation. At this time, Amazon Lex knows that the
user has not provided all the slot data to fulfill the intent.

49
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

• currentIntent information with all of the slot values set to null.


c. At this time, all the slot values are null. There is nothing for the Lambda function to validate.
The Lambda function returns the following response to Amazon Lex:

{
"sessionAttributes": {},
"dialogAction": {
"type": "Delegate",
"slots": {
"PickupTime": null,
"FlowerType": null,
"PickupDate": null
}
}
}

For information about the response format, see Response Format (p. 104).

Note the following:

• dialogAction.type – By setting this value to Delegate, Lambda function delegates the


responsibility of deciding the next course of action to Amazon Lex.
Note
If Lambda function detects anything in the user data validation, it instructs Amazon
Lex what to do next, as shown in the next few steps.
d. According to the dialogAction.type, Amazon Lex decides the next course of action. Because
none of the slots are filled, it decides to elicit the value for the FlowerType slot. It selects one
of the value elicitation prompts ("What type of flowers would you like to order?") for this slot
and sends the following response back to the client:

The client displays the message in the response.


2. User: roses

a. The client sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "roses",

50
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

"sessionAttributes": {}
}

In the request body, the inputText provides user input. The sessionAttributes remains
empty.
b. Amazon Lex first interprets the inputText in the context of the current intent. The service
remembers that it had asked the specific user for information about the FlowerType slot. It
updates the slot value in the current intent and invokes the Lambda function with the following
event data:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "ignw84y6seypre4xly5rimopuri2xwnd",
"sessionAttributes": {},
"bot": {
"name": "OrderFlowers",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "OrderFlowers",
"slots": {
"PickupTime": null,
"FlowerType": "roses",
"PickupDate": null
},
"confirmationStatus": "None"
}
}

Note the following:

• invocationSource – continues to be DialogCodeHook (we are simply validating user


data).
• currentIntent.slots – Amazon Lex has updated the FlowerType slot to roses.
c. According to the invocationSource value of DialogCodeHook, the Lambda function
performs user data validation. It recognizes roses as a valid slot value (and sets Price as a
session attribute) and returns the following response to Amazon Lex.

{
"sessionAttributes": {
"Price": 25
},
"dialogAction": {
"type": "Delegate",
"slots": {
"PickupTime": null,
"FlowerType": "roses",
"PickupDate": null
}
}
}

Note the following:

• sessionAttributes – Lambda function has added Price (of the roses) as a session
attribute.

51
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

• dialogAction.type – is set to Delegate. The user data was valid so the Lambda function
directs Amazon Lex to choose the next course of action.

 
d. According to the dialogAction.type, Amazon Lex chooses the next course of action. Amazon
Lex knows it needs more slot data so it picks the next unfilled slot (PickupDate) with the
highest priority according to the intent configuration. Amazon Lex selects one of the value-
elicitation prompt messages—"What day do you want the roses to be picked up?"—for this slot
according to the intent configuration, and then sends the following response back to the client:

The client simply displays the message in the response – "What day do you want the roses to be
picked up?."
3. User: tomorrow

a. The client sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "tomorrow",
"sessionAttributes": {
"Price": "25"
}
}

In the request body, inputText provides user input and the client passes the session attributes
back to the service.
b. Amazon Lex remembers the context—that it was eliciting data for the PickupDate slot. In this
context, it knows the inputText value is for the PickupDate slot. Amazon Lex then invokes
the Lambda function by sending the following event:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "ignw84y6seypre4xly5rimopuri2xwnd",
"sessionAttributes": {
"Price": "25"
},
"bot": {
"name": "OrderFlowersCustomWithRespCard",

52
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "OrderFlowers",
"slots": {
"PickupTime": null,
"FlowerType": "roses",
"PickupDate": "2017-01-05"
},
"confirmationStatus": "None"
}
}

Amazon Lex has updated the currentIntent.slots by setting the PickupDate value. Also
note that the service passes the sessionAttributes as it is to the Lambda function.
c. As per invocationSource value of DialogCodeHook, the Lambda function performs user
data validation. It recognizes PickupDate slot value is valid and returns the following response
to Amazon Lex:

{
"sessionAttributes": {
"Price": 25
},
"dialogAction": {
"type": "Delegate",
"slots": {
"PickupTime": null,
"FlowerType": "roses",
"PickupDate": "2017-01-05"
}
}
}

Note the following:

• sessionAttributes – No change.
• dialogAction.type – is set to Delegate. The user data was valid, and the Lambda
function directs Amazon Lex to choose the next course of action.
d. According to the dialogAction.type, Amazon Lex chooses the next course of action. Amazon
Lex knows it needs more slot data so it picks the next unfilled slot (PickupTime) with the
highest priority according to the intent configuration. Amazon Lex selects one of the prompt
messages ("Deliver the roses at what time on 2017-01-01?") for this slot according to the intent
configuration and sends the following response back to the client:

53
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

The client displays the message in the response – "Deliver the roses at what time on
2017-01-01?"
4. User: 4 pm

a. The client sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "4 pm",
"sessionAttributes": {
"Price": "25"
}
}

In the request body, inputText provides user input. The client passes the
sessionAttributes in the request.
b. Amazon Lex understands context. It understands that it was eliciting data for the PickupTime
slot. In this context, it knows that the inputText value is for the PickupTime slot. Amazon
Lex then invokes the Lambda function by sending the following event:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "ignw84y6seypre4xly5rimopuri2xwnd",
"sessionAttributes": {
"Price": "25"
},
"bot": {
"name": "OrderFlowersCustomWithRespCard",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "OrderFlowers",
"slots": {
"PickupTime": "16:00",
"FlowerType": "roses",
"PickupDate": "2017-01-05"
},
"confirmationStatus": "None"

54
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

}
}

Amazon Lex has updated the currentIntent.slots by setting the PickupTime value.
c. According to the invocationSource value of DialogCodeHook, the Lambda function
performs user data validation. It recognizes PickupDate slot value is valid and returns the
following response to Amazon Lex.

{
"sessionAttributes": {
"Price": 25
},
"dialogAction": {
"type": "Delegate",
"slots": {
"PickupTime": "16:00",
"FlowerType": "roses",
"PickupDate": "2017-01-05"
}
}
}

Note the following:

• sessionAttributes – No change in session attribute.


• dialogAction.type – is set to Delegate. The user data was valid so the Lambda function
directs Amazon Lex to choose the next course of action.
d. At this time Amazon Lex knows it has all the slot data. This intent is configured with a
confirmation prompt. Therefore, Amazon Lex sends the following response to the user asking
for confirmation before fulfilling the intent:

The client simply displays the message in the response and waits for the user response.
5. User: Yes

a. The client sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "yes",

55
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

"sessionAttributes": {
"Price": "25"
}
}

b. Amazon Lex interprets the inputText in the context of confirming the current intent. Amazon
Lex understands that the user wants to proceed with the order. This time Amazon Lex invokes
the Lambda function to fulfill the intent by sending the following event, which sets the
invocationSource to FulfillmentCodeHook in the event it sends to the Lambda function.
Amazon Lex also sets the confirmationStatus to Confirmed.

{
"messageVersion": "1.0",
"invocationSource": "FulfillmentCodeHook",
"userId": "ignw84y6seypre4xly5rimopuri2xwnd",
"sessionAttributes": {
"Price": "25"
},
"bot": {
"name": "OrderFlowersCustomWithRespCard",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "OrderFlowers",
"slots": {
"PickupTime": "16:00",
"FlowerType": "roses",
"PickupDate": "2017-01-05"
},
"confirmationStatus": "Confirmed"
}
}

Note the following:

• invocationSource – This time Amazon Lex set this value to FulfillmentCodeHook,


directing the Lambda function to fulfill the intent.
• confirmationStatus – is set to Confirmed.
c. This time, the Lambda function fulfills the OrderFlowers intent, and returns the following
response:

{
"sessionAttributes": {
"Price": "25"
},
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": "Thanks, your order for roses has been placed and will be
ready for pickup by 16:00 on 2017-01-05"
}
}
}

Note the following:

56
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

• Sets the dialogAction.type – The Lambda function sets this value to Close, directing
Amazon Lex to not expect a user response.
• dialogAction.fulfillmentState – is set to Fulfilled and includes an appropriate
message to convey to the user.
d. Amazon Lex reviews the fulfillmentState and sends the following response back to the
client.

Amazon Lex then returns the following to the client:

Note that:

• dialogState – Amazon Lex sets this value to fulfilled.


• message – is the same message that the Lambda function provided.

The client displays the message.


6. Now test the bot again. To establish a new (user) context, choose the Clear link in the test window.
Now provide invalid slot data for the OrderFlowers intent. This time the Lambda function
performs the data validation, resets invalid slot data value to null, and asks Amazon Lex to prompt
the user for valid data. For example, try the following:

• Jasmine as the flower type (it is not one of the supported flower types).
• Yesterday as the day when you want to pick up the flowers.
• After placing your order, enter another flower type instead of replying "yes" to confirm the order.
In response, the Lambda function updates the Price in the session attribute, keeping a running
total of flower orders.

The Lambda function also performs the fulfillment activity.

Next Step

Step 6: Update the Intent Configuration to Add an Utterance (Console) (p. 57)

Step 6: Update the Intent Configuration to Add an Utterance


(Console)
The OrderFlowers bot is configured with only two utterances. This provides limited information for
Amazon Lex to build a machine learning model that recognizes and responds to the user's intent. Try

57
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

typing "I want to order flowers" in the test window. Amazon Lex doesn’t recognize the text, and responds
with "I didn't understand you, what would you like to do?" You can improve the machine learning model
by adding more utterances.

Each utterance that you add provides Amazon Lex with more information about how to respond to your
users. You don't need to add an exact utterance, Amazon Lex generalizes from the samples that you
provide to recognize both exact matches and similar input.

To add an utterance (console)

1. Add the utterance "I want flowers" to the intent by typing it in the Sample utterances section of the
intent editor, and then clicking the plus icon next to the new utterance.

2. Build your bot to pick up the change. Choose Build, and then choose Build again.
3. Test your bot to confirm that it recognized the new utterance . In the test window, type "I want to
order flowers." Amazon Lex recognizes the phrase and responds with "What type of flowers would
you like to order?".

58
Amazon Lex Developer Guide
Exercise 1: Create a Bot Using a Blueprint

Next Step

Step 7 (Optional): Clean Up (Console) (p. 59)

Step 7 (Optional): Clean Up (Console)


Now, delete the resources that you created and clean up your account.

You can delete only resources that are not in use. In general, you should delete resources in the following
order:

• Delete bots to free up intent resources.


• Delete intents to free up slot type resources.
• Delete slot types last.

To clean up your account (console)

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. From the list of bots, choose the check box next to OrderFlowers.
3. To delete the bot, choose Delete, and then choose Continue in the confirmation dialog box.
4. In the left pane, choose Intents.
5. In the list of intents, choose OrderFlowersIntent.
6. To delete the intent, choose Delete, and then choose Continue in the confirmation dialog box.
7. In the left pane, choose Slot types.
8. In the list of slot types, choose Flowers.
9. To delete the slot type, choose Delete, and then choose Continue in the confirmation dialog box.

You have removed all of the resources that you created and cleaned up your account.

59
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

Exercise 2: Create a Custom Amazon Lex Bot


In this exercise, you use the Amazon Lex console to create a custom bot that orders pizza
(OrderPizzaBot). You configure the bot by adding a custom intent (OrderPizza), defining custom
slot types, and defining the slots required to fulfill a pizza order (pizza crust, size, and so on). For more
information about slot types and slots, see Amazon Lex: How It Works (p. 3).

Topics
• Step 1: Create a Lambda Function (p. 60)
• Step 2: Create a Bot (p. 62)
• Step 3: Build and Test the Bot (p. 67)
• Step 4 (Optional): Clean up (p. 70)

Step 1: Create a Lambda Function


First, create a Lambda function which fulfills a pizza order. You specify this function in your Amazon Lex
bot, which you create in the next section.

To create a Lambda function

1. Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2. Choose Create function.
3. On the Create function page, choose Author from scratch.

Because you are using custom code provided to you in this exercise to create a Lambda function, you
choose author the function from scratch.

Do the following:

a. Type the name (PizzaOrderProcessor).


b. For the Runtime, choose the latest version of Node.js.
c. For the Role, choose Create new role from template(s).
d. Enter a new role name (PizzaOrderProcessorRole).
e. Choose Create function.
4. On the function page, do the following:

In the Function code section, choose Edit code inline, and then copy the following Node.js function
code and paste it in the window.

'use strict';

// Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled


("Thanks, your pizza will arrive in 20 minutes")
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message,
},
};
}

60
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

// --------------- Events -----------------------

function dispatch(intentRequest, callback) {


console.log(`request received for userId=${intentRequest.userId}, intentName=
${intentRequest.currentIntent.name}`);
const sessionAttributes = intentRequest.sessionAttributes;
const slots = intentRequest.currentIntent.slots;
const crust = slots.crust;
const size = slots.size;
const pizzaKind = slots.pizzaKind;

callback(close(sessionAttributes, 'Fulfilled',
{'contentType': 'PlainText', 'content': `Okay, I have ordered your ${size}
${pizzaKind} pizza on ${crust} crust`}));

// --------------- Main handler -----------------------

// Route the incoming request based on intent.


// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {
try {
dispatch(event,
(response) => {
callback(null, response);
});
} catch (err) {
callback(err);
}
};

5. Choose Save.

Test the Lambda Function Using Sample Event Data


In the console, test the Lambda function by using sample event data to manually invoke it.

To test the Lambda function:

1. Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2. On the Lambda function page, choose the Lambda function (PizzaOrderProcessor).
3. On the function page, in the list of test events, choose Configure test events.
4. On the Configure test event page, do the following:

a. Choose Create new test event.


b. In the Event name field, enter a name for the event (PizzaOrderProcessorTest).
c. Copy the following Amazon Lex event into the window.

{
"messageVersion": "1.0",
"invocationSource": "FulfillmentCodeHook",
"userId": "user-1",
"sessionAttributes": {},
"bot": {
"name": "PizzaOrderingApp",
"alias": "$LATEST",
"version": "$LATEST"
},

61
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

"outputDialogMode": "Text",
"currentIntent": {
"name": "OrderPizza",
"slots": {
"size": "large",
"pizzaKind": "meat",
"crust": "thin"
},
"confirmationStatus": "None"
}
}

5. Choose Create.

AWS Lambda creates the test and you go back to the function page. Choose Test and Lambda executes
your Lambda function.

In the result box, choose Details. The console displays the following output in the Execution result pane.

{
"sessionAttributes": {},
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": "Okay, I have ordered your large meat pizza on thin crust."
}
}

Next Step
Step 2: Create a Bot (p. 62)

Step 2: Create a Bot


In this step, you create a bot to handle pizza orders.

Topics
• Create the Bot (p. 62)
• Create an Intent (p. 63)
• Create Slot Types (p. 63)
• Configure the Intent (p. 65)
• Configure the Bot (p. 66)

Create the Bot


Create the PizzaOrderingBot bot with the minimum information needed. You add an intent, an action
that the user wants to perform, for the bot later.

To create the bot

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. Create a bot.

62
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

a. If you are creating your first bot, choose Get Started. Otherwise, choose Bots, and then choose
Create.
b. On the Create your Lex bot page, choose Custom bot and provide the following information:

• App name: PizzaOrderingBot


• Output voice: Salli
• Session timeout : 5 minutes.
• Child-Directed: Choose the appropriate response.
c. Choose Create.

The console sends Amazon Lex a request to create a new bot. Amazon Lex sets the bot version
to $LATEST. After creating the bot, Amazon Lex shows the bot Editor tab:

• The bot version, Latest, appears next to the bot name in the console. New Amazon
Lex resources have $LATEST as the version. For more information, see Versioning and
Aliases (p. 97).
• Because you haven't created any intents or slots types, none are listed.
• Build and Publish are bot-level activities. After you configure the entire bot, you'll learn more
about these activities.

Next Step

Create an Intent (p. 63)

Create an Intent
Now, create the OrderPizza intent , an action that the user wants to perform, with the minimum
information needed. You add slot types for the intent and then configure the intent later.

To create an intent

1. In the Amazon Lex console, choose the plus sign (+) next to Intents, and then choose Create new
intent.
2. In the Create intent dialog box, type the name of the intent (OrderPizza), and then choose Add.

The console sends a request to Amazon Lex to create the OrderPizza intent. In this example you create
slots for the intent after you create slot types.

Next Step

Create Slot Types (p. 63)

Create Slot Types


Create the slot types, or parameter values, that the OrderPizza intent uses.

63
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

To create slot types

1. In the left menu, choose the plus sign (+) next to Slot types.
2. In the Add slot type dialog box, add the following:

• Slot type name – Crusts


• Description – Available crusts
• Choose Restrict to Slot values and Synonyms
• Value – Type thick. Press tab and in the Synonym field type stuffed. Choose the plus sign (+).
Type thin and then choose the plus sign (+) again.

The dialog should look like this:

3. Choose Add slot to intent.


4. On the Intent page, choose Required. Change the name of the slot from slotOne to crust.
Change the prompt to What kind of crust would you like?
5. Repeat Step 1 through Step 4 using the values in the following table:

Name Description Values Slot name Prompt

Sizes Available sizes small, medium, size What size pizza?


large

PizzaKind Available pizzas veg, cheese pizzaKind Do you want a


veg or cheese
pizza?

Next Step

Configure the Intent (p. 65)

64
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

Configure the Intent


Configure the OrderPizza intent to fulfill a user's request to order a pizza.

To configure an intent

• On the OrderPizza configuration page, configure the intent as follows:

• Sample utterances – Type the following strings. The curly braces {} enclose slot names.
• I want to order pizza please
• I want to order a pizza
• I want to order a {pizzaKind} pizza
• I want to order a {size} {pizzaKind} pizza
• I want a {size} {crust} crust {pizzaKind} pizza
• Can I get a pizza please
• Can I get a {pizzaKind} pizza
• Can I get a {size} {pizzaKind} pizza
• Lambda initialization and validation – Leave the default setting.
• Confirmation prompt – Leave the default setting.
• Fulfillment – Perform the following tasts:
• Choose AWS Lambda function.
• Choose PizzaOrderProcessor.
• If the Add permission to Lambda function dialog box is shown, choose OK to give the
OrderPizza intent permission to call the PizzaOrderProcessor Lambda function.
• Leave None selected.

The intent should look like the following:

65
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

Next Step

Configure the Bot (p. 66)

Configure the Bot


Configure error handling for the PizzaOrderingBot bot.

1. Navigate to the PizzaOrderingBot bot. Choose Editor. and then choose Error Handling.

66
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

2. Use the Editor tab to configure bot error handling.

• Information you provide in Clarification Prompts maps to the bot's clarificationPrompt


configuration.

When Amazon Lex can't determine the user intent, the service returns a response with this
message
• Information that you provide in the Hang-up phrase maps to the bot's abortStatement
configuration.

If the service can't determine the user's intent after a set number of consecutive requests, Amazon
Lex returns a response with this message.

Leave the defaults.

Next Step

Step 3: Build and Test the Bot (p. 67)

Step 3: Build and Test the Bot


Make sure the bot works, by building and testing it.

To build and test the bot

1. To build the PizzaOrderingBot bot, choose Build.

Amazon Lex builds a machine learning model for the bot. When you test the bot, the console uses
the runtime API to send the user input back to Amazon Lex. Amazon Lex then uses the machine
learning model to interpret the user input.

It can take some time to complete the build.


2. To test the bot, in the Test Bot window, start communicating with your Amazon Lex bot.

• For example, you might say or type:

67
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

• Use the sample utterances that you configured in the OrderPizza intent to test the bot. For
example, the following is one of the sample utterances that you configured for the PizzaOrder
intent:

I want a {size} {crust} crust {pizzaKind} pizza

To test it, type the following:

I want a large thin crust cheese pizza

When you type "I want to order a pizza," Amazon Lex detects the intent (OrderPizza). Then,
Amazon Lex asks for slot information.

After you provide all of the slot information, Amazon Lex invokes the Lambda function that you
configured for the intent.

The Lambda function returns a message ("Okay, I have ordered your ...") to Amazon Lex, which
Amazon Lex returns to you..

Inspecting the Response


Underneath the chat window is a pane that enables you to inspect the response from Amazon Lex. The
pane provides comprehensive information about the state of your bot that changes as you interact with
your bot.

The contents of the pane show you the current state of the operation.

68
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

• Dialog State – The current state of the conversation with the user. It can be ElicitIntent,
ElicitSlot, ConfirmIntent or Fulfilled.

 
• Summary – Shows a simplified view of the dialog that shows the slot values for the intent being
fulfilled so that you can keep track of the information flow. It shows the intent name, the number of
slots and the number of slots filled, and a list of all of the slots and their associated values.

• Detail – Shows the raw JSON response from the chatbot to give you a deeper view into the bot
interaction and the current state of the dialog as you test and debug your chatbot. If you type
in the chat window, the inspection pane shows the JSON response from the PostText (p. 335)
operation. If you speak to the chat window, the inspection pane shows the response headers from the
PostContent (p. 327) operation.

69
Amazon Lex Developer Guide
Exercise 2: Create a Custom Bot

Next Step
Step 4 (Optional): Clean up (p. 70)

Step 4 (Optional): Clean up


Delete the resources that you created and clean up your account to avoid incurring more charges for the
resources you created.

You can delete only resources that are not in use. For example, you cannot delete a slot type that is
referenced by an intent. You cannot delete an intent that is referenced by a bot.

Delete resources in the following order:

• Delete bots to free up intent resources.


• Delete intents to free up slot type resources.
• Delete slot types last.

To clean up your account

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. From the list of bots, choose PizzaOrderingBot.
3. To delete the bot, choose Delete, and then choose Continue.
4. In the left pane, choose Intents.
5. In the list of intents, choose OrderPizza.

70
Amazon Lex Developer Guide
Exercise 3: Publish a Version and Create an Alias

6. To delete the intent, choose Delete, and then choose Continue.


7. In the left menu, choose Slot types.
8. In the list of slot types, choose Crusts.
9. To delete the slot type, choose Delete, and then choose Continue.
10. Repeat Step 8 and Step 9 for the Sizes and PizzaKind slot types.

You have removed all of the resources that you created and cleaned up your account.

Next Steps
• Publish a Version and Create an Alias
• Create an Amazon Lex bot with the AWS Command Line Interface

Exercise 3: Publish a Version and Create an Alias


In Getting Started Exercises 1 and 2, you created a bot and tested it. In this exercise, you do the
following:

• Publish a new version of the bot. Amazon Lex takes a snapshot copy of the $LATEST version to publish
a new version.
• Create an alias that points to the new version.

For more information about versioning and aliases, see Versioning and Aliases (p. 97).

Do the following to publish a version of a bot you created for this exercise:

1. In the Amazon Lex console, choose one of the bots you created.

Verify that the console shows the $LATEST as the bot version next to the bot name.
2. Choose Publish.
3. On the Publish botname wizard, specify the alias BETA, and then choose Publish.
4. Verify that the Amazon Lex console shows the new version next to the bot name.

Now that you have a working bot with published version and an alias, you can deploy the bot (in your
mobile application or integrate the bot with Facebook Messenger). For an example, see Integrating an
Amazon Lex Bot with Facebook Messenger (p. 111).

71
Amazon Lex Developer Guide
Step 4: Getting Started (AWS CLI)

Step 4: Getting Started (AWS CLI)


In this step, you use the AWS CLI to create, test, and modify an Amazon Lex bot. To complete these
exercises, you need to be familiar with using the CLI and have a text editor. For more information, see
Step 2: Set Up the AWS Command Line Interface (p. 32)

• Exercise 1 — Create and test an Amazon Lex bot. The exercise provides all of the JSON objects that you
need to create a custom slot type, an intent, and a bot. For more information, see Amazon Lex: How It
Works (p. 3)
• Exercise 2 — Update the bot that you created in Exercise 1 to add an additional sample utterance.
Amazon Lex uses sample utterances to build the machine learning model for your bot.
• Exercise 3 — Update the bot that you created in Exercise 1 to add a Lambda function to validate user
input and to fulfill the intent.
• Exercise 4 — Publish a version of the slot type, intent, and bot resources that you created in Exercise 1.
A version is a snapshot of a resource that can't be changed.
• Exercise 5 — Create an alias for the bot that you created in Exercise 1.
• Exercise 6 — Clean up your account by deleting the slot type, intent, and bot that you created in
Exercise 1, and the alias that you created in Exercise 5.

Topics
• Exercise 1: Create an Amazon Lex Bot (AWS CLI) (p. 72)
• Exercise 2: Add a New Utterance (AWS CLI) (p. 84)
• Exercise 3: Add a Lambda Function (AWS CLI) (p. 88)
• Exercise 4: Publish a Version (AWS CLI) (p. 91)
• Exercise 5: Create an Alias (AWS CLI) (p. 95)
• Exercise 6: Clean Up (AWS CLI) (p. 96)

Exercise 1: Create an Amazon Lex Bot (AWS CLI)


In general, when you create bots, you:

1. Create slot types to define the information that your bot will be working with.
2. Create intents that define the user actions that your bot supports. Use the custom slot types that you
created earlier to define the slots, or parameters, that your intent requires.
3. Create a bot that uses the intents that you defined.

In this exercise you create and test a new Amazon Lex bot using the CLI. Use the JSON structures that we
provide to create the bot. To run the commands in this exercise, you need to know the region where the
commands will be run. For a list of regions, see Model Building Limits (p. 187).

Topics
• Step 1: Create a Service-Linked Role (AWS CLI) (p. 73)
• Step 2: Create a Custom Slot Type (AWS CLI) (p. 73)
• Step 3: Create an Intent (AWS CLI) (p. 75)
• Step 4: Create a Bot (AWS CLI) (p. 78)
• Step 5: Test a Bot (AWS CLI) (p. 80)

72
Amazon Lex Developer Guide
Exercise 1: Create a Bot

Step 1: Create a Service-Linked Role (AWS CLI)


Amazon Lex assumes AWS Identity and Access Management service-linked roles to call AWS services on
behalf of your bots. The roles, which are in your account, are linked to Amazon Lex use cases and have
predefined permissions. For more information, see Service Permissions (p. 8).

If you've already created an Amazon Lex bot using the console, the service-linked role was created
automatically. Skip to Step 2: Create a Custom Slot Type (AWS CLI) (p. 73).

To create a service-linked role (AWS CLI)

1. In the AWS CLI, type the following command:

aws iam create-service-linked-role --aws-service-name lex.amazonaws.com

2. Check the policy using the following command:

aws iam get-role --role-name AWSServiceRoleForLexBots

The response is:

{
"Role": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lex.amazonaws.com"
}
}
]
},
"RoleName": "AWSServiceRoleForLexBots",
"Path": "/aws-service-role/lex.amazonaws.com/",
"Arn": "arn:aws:iam::account-id:role/aws-service-role/lex.amazonaws.com/
AWSServiceRoleForLexBots"
}

Next Step
Step 2: Create a Custom Slot Type (AWS CLI) (p. 73)

Step 2: Create a Custom Slot Type (AWS CLI)


Create a custom slot type with enumeration values for the flowers that can be ordered. You use this type
in the next step when you create the OrderFlowers intent. A slot type defines the possible values for a
slot, or parameter, of the intent.

To run the commands in this exercise, you need to know the region where the commands will be run. For
a list of regions, see Model Building Limits (p. 187).

To create a custom slot type (AWS CLI)

1. Create a text file named FlowerTypes.json. Copy the JSON code from FlowerTypes.json (p. 74)
into the text file.

73
Amazon Lex Developer Guide
Exercise 1: Create a Bot

2. Call the PutSlotType (p. 319) operation using the AWS CLI to create the slot type. The example
is formatted for Unix, Linux, and macOS. For Windows, replace the backslash (\) Unix continuation
character at the end of each line with a caret (^).

aws lex-models put-slot-type \


--region region \
--name FlowerTypes \
--cli-input-json file://FlowerTypes.json

The response from the server is:

{
"enumerationValues": [
{
"value": "tulips"
},
{
"value": "lilies"
},
{
"value": "roses"
}
],
"name": "FlowerTypes",
"checksum": "checksum",
"version": "$LATEST",
"lastUpdatedDate": timestamp,
"createdDate": timestamp,
"description": "Types of flowers to pick up"
}

Next Step
Step 3: Create an Intent (AWS CLI) (p. 75)

FlowerTypes.json
The following code is the JSON data required to create the FlowerTypes custom slot type:

{
"enumerationValues": [
{
"value": "tulips"
},
{
"value": "lilies"
},
{
"value": "roses"
}
],
"name": "FlowerTypes",
"description": "Types of flowers to pick up"
}

74
Amazon Lex Developer Guide
Exercise 1: Create a Bot

Step 3: Create an Intent (AWS CLI)


Create an intent for the OrderFlowersBot bot and provide three slots, or parameters. The slots allow
the bot to fulfill the intent:

• FlowerType is a custom slot type that specifies which types of flowers can be ordered.
• AMAZON.DATE and AMAZON.TIME are built-in slot types used for getting the date and time to deliver
the flowers from the user.

To run the commands in this exercise, you need to know the region where the commands will be run. For
a list of regions, see Model Building Limits (p. 187).

To create the OrderFlowers intent (AWS CLI)

1. Create a text file named OrderFlowers.json. Copy the JSON code from
OrderFlowers.json (p. 77) into the text file.
2. In the AWS CLI, call the PutIntent (p. 309) operation to create the intent. The example is formatted
for Unix, Linux, and macOS. For Windows, replace the backslash (\) Unix continuation character at
the end of each line with a caret (^).

aws lex-models put-intent \


--region region \
--name OrderFlowers \
--cli-input-json file://OrderFlowers.json

The server responds with the following:

{
"confirmationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "Okay, your {FlowerType} will be ready for pickup by
{PickupTime} on {PickupDate}. Does this sound okay?",
"contentType": "PlainText"
}
]
},
"name": "OrderFlowers",
"checksum": "checksum",
"version": "$LATEST",
"rejectionStatement": {
"messages": [
{
"content": "Okay, I will not place your order.",
"contentType": "PlainText"
}
]
},
"createdDate": timestamp,
"lastUpdatedDate": timestamp,
"sampleUtterances": [
"I would like to pick up flowers",
"I would like to order some flowers"
],
"slots": [
{
"slotType": "AMAZON.TIME",
"name": "PickupTime",
"slotConstraint": "Required",

75
Amazon Lex Developer Guide
Exercise 1: Create a Bot

"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "Pick up the {FlowerType} at what time on
{PickupDate}?",
"contentType": "PlainText"
}
]
},
"priority": 3,
"description": "The time to pick up the flowers"
},
{
"slotType": "FlowerTypes",
"name": "FlowerType",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What type of flowers would you like to order?",
"contentType": "PlainText"
}
]
},
"priority": 1,
"slotTypeVersion": "$LATEST",
"sampleUtterances": [
"I would like to order {FlowerType}"
],
"description": "The type of flowers to pick up"
},
{
"slotType": "AMAZON.DATE",
"name": "PickupDate",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What day do you want the {FlowerType} to be picked
up?",
"contentType": "PlainText"
}
]
},
"priority": 2,
"description": "The date to pick up the flowers"
}
],
"fulfillmentActivity": {
"type": "ReturnIntent"
},
"description": "Intent to order a bouquet of flowers for pick up"
}

Next Step
Step 4: Create a Bot (AWS CLI) (p. 78)

76
Amazon Lex Developer Guide
Exercise 1: Create a Bot

OrderFlowers.json
The following code is the JSON data required to create the OrderFlowers intent:

{
"confirmationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "Okay, your {FlowerType} will be ready for pickup by
{PickupTime} on {PickupDate}. Does this sound okay?",
"contentType": "PlainText"
}
]
},
"name": "OrderFlowers",
"rejectionStatement": {
"messages": [
{
"content": "Okay, I will not place your order.",
"contentType": "PlainText"
}
]
},
"sampleUtterances": [
"I would like to pick up flowers",
"I would like to order some flowers"
],
"slots": [
{
"slotType": "FlowerTypes",
"name": "FlowerType",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What type of flowers would you like to order?",
"contentType": "PlainText"
}
]
},
"priority": 1,
"slotTypeVersion": "$LATEST",
"sampleUtterances": [
"I would like to order {FlowerType}"
],
"description": "The type of flowers to pick up"
},
{
"slotType": "AMAZON.DATE",
"name": "PickupDate",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What day do you want the {FlowerType} to be picked
up?",
"contentType": "PlainText"
}
]
},
"priority": 2,
"description": "The date to pick up the flowers"

77
Amazon Lex Developer Guide
Exercise 1: Create a Bot

},
{
"slotType": "AMAZON.TIME",
"name": "PickupTime",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "Pick up the {FlowerType} at what time on
{PickupDate}?",
"contentType": "PlainText"
}
]
},
"priority": 3,
"description": "The time to pick up the flowers"
}
],
"fulfillmentActivity": {
"type": "ReturnIntent"
},
"description": "Intent to order a bouquet of flowers for pick up"
}

Step 4: Create a Bot (AWS CLI)


The OrderFlowersBot bot has one intent, the OrderFlowers intent that you created in the previous
step. To run the commands in this exercise, you need to know the region where the commands will be
run. For a list of regions, see Model Building Limits (p. 187).
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST.

To create the OrderFlowersBot bot (AWS CLI)

1. Create a text file named OrderFlowersBot.json. Copy the JSON code from
OrderFlowersBot.json (p. 79) into the text file.
2. In the AWS CLI, call the PutBot (p. 297) operation to create the bot. The example is formatted for
Unix, Linux, and macOS. For Windows, replace the backslash (\) Unix continuation character at the
end of each line with a caret (^).

aws lex-models put-bot \


--region region \
--name OrderFlowersBot \
--cli-input-json file://OrderFlowersBot.json

The response from the server follows. When you create or update bot, the status field is set to
BUILDING. This indicates that the bot isn't ready to use. To determine when the bot is ready for use,
use the GetBot (p. 238) operation in the next step .

{
"status": "BUILDING",
"intents": [
{
"intentVersion": "$LATEST",
"intentName": "OrderFlowers"
}
],
"name": "OrderFlowersBot",

78
Amazon Lex Developer Guide
Exercise 1: Create a Bot

"locale": "en-US",
"checksum": "checksum",
"abortStatement": {
"messages": [
{
"content": "Sorry, I'm not able to assist at this time",
"contentType": "PlainText"
}
]
},
"version": "$LATEST",
"lastUpdatedDate": timestamp,
"createdDate": timestamp,
"clarificationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "I didn't understand you, what would you like to do?",
"contentType": "PlainText"
}
]
},
"voiceId": "Salli",
"childDirected": false,
"idleSessionTTLInSeconds": 600,
"processBehavior": "BUILD",
"description": "Bot to order flowers on the behalf of a user"
}

3. To determine if your new bot is ready for use, run the following command. Repeat this command
until the status field returns READY. The example is formatted for Unix, Linux, and macOS. For
Windows, replace the backslash (\) Unix continuation character at the end of each line with a caret
(^).

aws lex-models get-bot \


--region region \
--name OrderFlowersBot \
--version-or-alias "\$LATEST"

Look for the status field in the response:

{
"status": "READY",

...

Next Step
Step 5: Test a Bot (AWS CLI) (p. 80)

OrderFlowersBot.json
The following code provides the JSON data required to build the OrderFlowers Amazon Lex bot:

{
"intents": [
{
"intentVersion": "$LATEST",

79
Amazon Lex Developer Guide
Exercise 1: Create a Bot

"intentName": "OrderFlowers"
}
],
"name": "OrderFlowersBot",
"locale": "en-US",
"abortStatement": {
"messages": [
{
"content": "Sorry, I'm not able to assist at this time",
"contentType": "PlainText"
}
]
},
"clarificationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "I didn't understand you, what would you like to do?",
"contentType": "PlainText"
}
]
},
"voiceId": "Salli",
"childDirected": false,
"idleSessionTTLInSeconds": 600,
"description": "Bot to order flowers on the behalf of a user"
}

Step 5: Test a Bot (AWS CLI)


To test the bot,you can use either a text-based or a speech-based test.

Topics
• Test the Bot Using Text Input (AWS CLI) (p. 80)
• Test the Bot Using Speech Input (AWS CLI) (p. 82)

Test the Bot Using Text Input (AWS CLI)


To verify that the bot works correctly with text input, use the PostText (p. 335) operation. To run the
commands in this exercise, you need to know the region where the commands will be run. For a list of
regions, see Runtime Service Limits (p. 186).
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST and replace the backslash (\) continuation character at the end of
each line with a caret (^).

To use text to test the bot (AWS CLI)

1. In the AWS CLI, start a conversation with the OrderFlowersBot bot. The example is formatted for
Unix, Linux, and macOS. For Windows, replace the backslash (\) Unix continuation character at the
end of each line with a caret (^).

aws lex-runtime post-text \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--input-text "i would like to order flowers"

80
Amazon Lex Developer Guide
Exercise 1: Create a Bot

Amazon Lex recognizes the user's intent and starts a conversation by returning the following
response:

{
"slotToElicit": "FlowerType",
"slots": {
"PickupDate": null,
"PickupTime": null,
"FlowerType": null
},
"dialogState": "ElicitSlot",
"message": "What type of flowers would you like to order?",
"intentName": "OrderFlowers"
}

2. Run the following commands to finish the conversation with the bot.

aws lex-runtime post-text \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--input-text "roses"

aws lex-runtime post-text \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--input-text "tuesday"

aws lex-runtime post-text \


--region region \
--bot-name OrderFlowersBot --bot-alias "\$LATEST" \
--user-id UserOne \
--input-text "10:00 a.m."

aws lex-runtime post-text \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--input-text "yes"

After you confirm the order, Amazon Lex sends a fulfillment response to complete the conversation:

{
"slots": {
"PickupDate": "2017-05-16",
"PickupTime": "10:00",
"FlowerType": "roses"
},
"dialogState": "ReadyForFulfillment",
"intentName": "OrderFlowers"
}

81
Amazon Lex Developer Guide
Exercise 1: Create a Bot

Next Step

Test the Bot Using Speech Input (AWS CLI) (p. 82)

Test the Bot Using Speech Input (AWS CLI)


To test the bot using audio files, use the PostContent (p. 327) operation. You generate the audio files
using Amazon Polly text-to-speech operations.

To run the commands in this exercise, you need to know the region the Amazon Lex and Amazon Polly
commands will be run. For a list of regions for Amazon Lex, see Runtime Service Limits (p. 186). For a
list of regions for Amazon Polly see AWS Regions and Endpoints in the Amazon Web Services General
Reference.
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST and replace the backslash (\) continuation character at the end of
each line with a caret (^).

To use a speech input to test the bot (AWS CLI)

1. In the AWS CLI, create an audio file using Amazon Polly. The example is formatted for Unix, Linux,
and macOS. For Windows, replace the backslash (\) Unix continuation character at the end of each
line with a caret (^).

aws polly synthesize-speech \


--region region \
--output-format pcm \
--text "i would like to order flowers" \
--voice-id "Kendra" \
IntentSpeech.mpg

2. To send the audio file to Amazon Lex, run the following command. Amazon Lex saves the audio from
the response in the specified output file.

aws lex-runtime post-content \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--content-type "audio/l16; rate=16000; channels=1" \
--input-stream IntentSpeech.mpg \
IntentOutputSpeech.mpg

Amazon Lex responds with a request for the first slot. It saves the audio response in the specified
output file.

{
"contentType": "audio/mpeg",
"slotToElicit": "FlowerType",
"dialogState": "ElicitSlot",
"intentName": "OrderFlowers",
"inputTranscript": "i would like to order some flowers",
"slots": {
"PickupDate": null,
"PickupTime": null,
"FlowerType": null
},
"message": "What type of flowers would you like to order?"
}

82
Amazon Lex Developer Guide
Exercise 1: Create a Bot

3. To order roses, create the following audio file and send it to Amazon Lex :

aws polly synthesize-speech \


--region region \
--output-format pcm \
--text "roses" \
--voice-id "Kendra"
FlowerTypeSpeech.mpg

aws lex-runtime post-content \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--content-type "audio/l16; rate=16000; channels=1" \
--input-stream FlowerTypeSpeech.mpg \
FlowerTypeOutputSpeech.mpg

4. To set the delivery date, create the following audio file and send it to Amazon Lex:

aws polly synthesize-speech \


--region region \
--output-format pcm \
--text "tuesday" \
--voice-id "Kendra"
DateSpeech.mpg

aws lex-runtime post-content \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--content-type "audio/l16; rate=16000; channels=1" \
--input-stream DateSpeech.mpg
DateOutputSpeech.mpg

5. To set the delivery time, create the following audio file and send it to Amazon Lex:

aws polly synthesize-speech \


--region region \
--output-format pcm \
--text "10:00 a.m." \
--voice-id "Kendra"
TimeSpeech.mpg

aws lex-runtime post-content \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--content-type "audio/l16; rate=16000; channels=1" \
--input-stream TimeSpeech.mpg
TimeOutputSpeech.mpg

6. To confirm the delivery, create the following audio file and send it to Amazon Lex:

aws polly synthesize-speech \


--region region \
--output-format pcm \

83
Amazon Lex Developer Guide
Exercise 2: Add a New Utterance

--text "yes" \
--voice-id "Kendra"
ConfirmSpeech.mpg

aws lex-runtime post-content \


--region region \
--bot-name OrderFlowersBot \
--bot-alias "\$LATEST" \
--user-id UserOne \
--content-type "audio/l16; rate=16000; channels=1" \
--input-stream ConfirmSpeech.mpg \
ConfirmOutputSpeech.mpg

After you confirm the delivery, Amazon Lex sends a response that confirms fulfillment of the intent:

{
"contentType": "text/plain;charset=utf-8",
"dialogState": "ReadyForFulfillment",
"intentName": "OrderFlowers",
"inputTranscript": "yes",
"slots": {
"PickupDate": "2017-05-16",
"PickupTime": "10:00",
"FlowerType": "roses"
}
}

Next Step

Exercise 2: Add a New Utterance (AWS CLI) (p. 84)

Exercise 2: Add a New Utterance (AWS CLI)


To improve the machine learning model that Amazon Lex uses to recognize requests from your users,
add another sample utterance to the bot.

Adding a new utterance is a four-step process.

1. Use the GetIntent (p. 274) operation to get an intent from Amazon Lex.
2. Update the intent.
3. Use the PutIntent (p. 309) operation to send the updated intent back to Amazon Lex.
4. Use the GetBot (p. 238) and PutBot (p. 297) operations to rebuild any bot that uses the intent.

To run the commands in this exercise, you need to know the region where the commands will be run. For
a list of regions, see Model Building Limits (p. 187).

The response from the GetIntent operation contains a field called checksum that identifies a specific
revision of the intent. You must provide the checksum value when you use the PutIntent (p. 309)
operation to update an intent. If you don't, you'll get the following error message:

An error occurred (PreconditionFailedException) when calling


the PutIntent operation: Intent intent name already exists.
If you are trying to update intent name you must specify the
checksum.

84
Amazon Lex Developer Guide
Exercise 2: Add a New Utterance

Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST and replace the backslash (\) continuation character at the end of
each line with a caret (^).

To update the OrderFlowers intent (AWS CLI)

1. In the AWS CLI, get the intent from Amazon Lex. Amazon Lex sends the output to a file called
OrderFlowers-V2.json.

aws lex-models get-intent \


--region region \
--name OrderFlowers \
--intent-version "\$LATEST" > OrderFlowers-V2.json

2. Open OrderFlowers-V2.json in a text editor.

1. Find and delete the createdDate, lastUpdatedDate, and version fields.


2. Add the following to the sampleUtterances field:

I want to order flowers

3. Save the file.


3. Send the updated intent to Amazon Lex with the following command:

aws lex-models put-intent \


--region region \
--name OrderFlowers \
--cli-input-json file://OrderFlowers-V2.json

Amazon Lex sends the following response:

{
"confirmationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "Okay, your {FlowerType} will be ready for pickup by
{PickupTime} on {PickupDate}. Does this sound okay?",
"contentType": "PlainText"
}
]
},
"name": "OrderFlowers",
"checksum": "checksum",
"version": "$LATEST",
"rejectionStatement": {
"messages": [
{
"content": "Okay, I will not place your order.",
"contentType": "PlainText"
}
]
},
"createdDate": timestamp,
"lastUpdatedDate": timestamp,
"sampleUtterances": [
"I would like to pick up flowers",

85
Amazon Lex Developer Guide
Exercise 2: Add a New Utterance

"I would like to order some flowers",


"I want to order flowers"
],
"slots": [
{
"slotType": "AMAZON.TIME",
"name": "PickupTime",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "Pick up the {FlowerType} at what time on
{PickupDate}?",
"contentType": "PlainText"
}
]
},
"priority": 3,
"description": "The time to pick up the flowers"
},
{
"slotType": "FlowerTypes",
"name": "FlowerType",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What type of flowers would you like to order?",
"contentType": "PlainText"
}
]
},
"priority": 1,
"slotTypeVersion": "$LATEST",
"sampleUtterances": [
"I would like to order {FlowerType}"
],
"description": "The type of flowers to pick up"
},
{
"slotType": "AMAZON.DATE",
"name": "PickupDate",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What day do you want the {FlowerType} to be picked
up?",
"contentType": "PlainText"
}
]
},
"priority": 2,
"description": "The date to pick up the flowers"
}
],
"fulfillmentActivity": {
"type": "ReturnIntent"
},
"description": "Intent to order a bouquet of flowers for pick up"
}

86
Amazon Lex Developer Guide
Exercise 2: Add a New Utterance

Now that you have updated the intent, rebuild any bot that uses it.

To rebuild the OrderFlowersBot bot (AWS CLI)

1. In the AWS CLI, get the definition of the OrderFlowersBot bot and save it to a file with the
following command:

aws lex-models get-bot \


--region region \
--name OrderFlowersBot \
--version-or-alias "\$LATEST" > OrderFlowersBot-V2.json

2. In a text editor, open OrderFlowersBot-V2.json. Remove the createdDate,


lastUpdatedDate, status and version fields.
3. In a text editor, add the following line to the bot definition:

"processBehavior": "BUILD",

4. In the AWS CLI, build a new revision of the bot by running the following command to :

aws lex-models put-bot \


--region region \
--name OrderFlowersBot \
--cli-input-json file://OrderFlowersBot-V2.json

The response from the server is:

{
"status": "BUILDING",
"intents": [
{
"intentVersion": "$LATEST",
"intentName": "OrderFlowers"
}
],
"name": "OrderFlowersBot",
"locale": "en-US",
"checksum": "checksum",
"abortStatement": {
"messages": [
{
"content": "Sorry, I'm not able to assist at this time",
"contentType": "PlainText"
}
]
},
"version": "$LATEST",
"lastUpdatedDate": timestamp,
"createdDate": timestamp
"clarificationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "I didn't understand you, what would you like to do?",
"contentType": "PlainText"
}
]
},
"voiceId": "Salli",
"childDirected": false,
"idleSessionTTLInSeconds": 600,

87
Amazon Lex Developer Guide
Exercise 3: Add a Lambda Function

"description": "Bot to order flowers on the behalf of a user"


}

Next Step
Exercise 3: Add a Lambda Function (AWS CLI) (p. 88)

Exercise 3: Add a Lambda Function (AWS CLI)


Add a Lambda function that validates user input and fulfills the user's intent to the bot.

Adding a Lambda expression is a five-step process.

1. Use the Lambda AddPermission function to enable the OrderFlowers intent to call the Lambda
Invoke operation.
2. Use the GetIntent (p. 274) operation to get the intent from Amazon Lex.
3. Update the intent to add the Lambda function.
4. Use the PutIntent (p. 309) operation to send the updated intent back to Amazon Lex.
5. Use the GetBot (p. 238) and PutBot (p. 297) operations to rebuild any bot that uses the intent.

To run the commands in this exercise, you need to know the region where the commands will be run. For
a list of regions, see Model Building Limits (p. 187).

If you add a Lambda function to an intent before you add the InvokeFunction permission, you get the
following error message:

An error occurred (BadRequestException) when calling the


PutIntent operation: Lex is unable to access the Lambda
function Lambda function ARN in the context of intent
intent ARN. Please check the resource-based policy on
the function.

The response from the GetIntent operation contains a field called checksum that identifies a specific
revision of the intent. When you use the PutIntent (p. 309) operation to update an intent, you must
provide the checksum value. If you don't, you get the following error message:

An error occurred (PreconditionFailedException) when calling


the PutIntent operation: Intent intent name already exists.
If you are trying to update intent name you must specify the
checksum.

This exercise uses the Lambda function from Exercise 1: Create an Amazon Lex Bot Using a Blueprint
(Console) (p. 33). For instructions to create the Lambda function, see Step 3: Create a Lambda
Function (Console) (p. 45).
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST.

To add a Lambda function to an intent

1. In the AWS CLI, add the InvokeFunction permission for the OrderFlowers intent:

88
Amazon Lex Developer Guide
Exercise 3: Add a Lambda Function

aws lambda add-permission \


--region region \
--function-name OrderFlowersCodeHook \
--statement-id LexGettingStarted-OrderFlowersBot \
--action lambda:InvokeFunction \
--principal lex.amazonaws.com \
--source-arn "arn:aws:lex:region:account ID:intent:OrderFlowers:*"

Lambda sends the following response:

{
"Statement": "{\"Sid\":\"LexGettingStarted-OrderFlowersBot\",
\"Resource\":\"arn:aws:lambda:region:account ID:function:OrderFlowersCodeHook\",
\"Effect\":\"Allow\",
\"Principal\":{\"Service\":\"lex.amazonaws.com\"},
\"Action\":[\"lambda:InvokeFunction\"],
\"Condition\":{\"ArnLike\":
{\"AWS:SourceArn\":
\"arn:aws:lex:region:account ID:intent:OrderFlowers:*\"}}}"
}

2. Get the intent from Amazon Lex. Amazon Lex sends the output to a file called OrderFlowers-
V3.json.

aws lex-models get-intent \


--region region \
--name OrderFlowers \
--intent-version "\$LATEST" > OrderFlowers-V3.json

3. In a text editor, open the OrderFlowers-V3.json.

1. Find and delete the createdDate, lastUpdatedDate, and version fields.


2. Update the fulfillmentActivity field :

"fulfillmentActivity": {
"type": "CodeHook",
"codeHook": {
"uri": "arn:aws:lambda:region:account ID:function:OrderFlowersCodeHook",
"messageVersion": "1.0"
}
}

3. Save the file.


4. In the AWS CLI, send the updated intent to Amazon Lex:

aws lex-models put-intent \


--region region \
--name OrderFlowers \
--cli-input-json file://OrderFlowers-V3.json

Now that you have updated the intent, rebuild the bot.

To rebuild the OrderFlowersBot bot

1. In the AWS CLI, get the definition of the OrderFlowersBot bot and save it to a file:

aws lex-models get-bot \

89
Amazon Lex Developer Guide
Exercise 3: Add a Lambda Function

--region region \
--name OrderFlowersBot \
--version-or-alias "\$LATEST" > OrderFlowersBot-V3.json

2. In a text editor,open OrderFlowersBot-V3.json. Remove the createdDate,


lastUpdatedDate, status, and version fields.
3. In the text editor, add the following line to the definition of the bot:

"processBehavior": "BUILD",

4. In the AWS CLI, build a new revision of the bot:

aws lex-models put-bot \


--region region \
--name OrderFlowersBot \
--cli-input-json file://OrderFlowersBot-V3.json

The response from the server is:

{
"status": "READY",
"intents": [
{
"intentVersion": "$LATEST",
"intentName": "OrderFlowers"
}
],
"name": "OrderFlowersBot",
"locale": "en-US",
"checksum": "checksum",
"abortStatement": {
"messages": [
{
"content": "Sorry, I'm not able to assist at this time",
"contentType": "PlainText"
}
]
},
"version": "$LATEST",
"lastUpdatedDate": timestamp,
"createdDate": timestamp,
"clarificationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "I didn't understand you, what would you like to do?",
"contentType": "PlainText"
}
]
},
"voiceId": "Salli",
"childDirected": false,
"idleSessionTTLInSeconds": 600,
"description": "Bot to order flowers on the behalf of a user"
}

Next Step
Exercise 4: Publish a Version (AWS CLI) (p. 91)

90
Amazon Lex Developer Guide
Exercise 4: Publish a Version

Exercise 4: Publish a Version (AWS CLI)


Now, create a version of the bot that you created in Exercise 1. A version is a snapshot of the bot. After
you create a version, you can’t change it. The only version of a bot that you can update is the $LATEST
version. For more information about versions, see Versioning and Aliases (p. 97).

Before you can publish a version of a bot, you must publish the intents that is uses. Likewise, you must
publish the slot types that those intents refer to. In general, to publish a version of a bot, you do the
following:

1. Publish a version of a slot type with the CreateSlotTypeVersion (p. 216) operation.
2. Publish a version of an intent with the CreateIntentVersion (p. 210) operation.
3. Publish a version of a bot with the CreateBotVersion (p. 205) operation .

To run the commands in this exercise, you need to know the region where the commands will be run. For
a list of regions, see Model Building Limits (p. 187).

Topics
• Step 1: Publish the Slot Type (AWS CLI) (p. 91)
• Step 2: Publish the Intent (AWS CLI) (p. 92)
• Step 3: Publish the Bot (AWS CLI) (p. 94)

Step 1: Publish the Slot Type (AWS CLI)


Before you can publish a version of any intents that use a slot type, you must publish a version of that
slot type. In this case, you publish the FlowerTypes slot type.
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST and replace the backslash (\) continuation character at the end of
each line with a caret (^).

To publish a slot type (AWS CLI)

1. In the AWS CLI, get the latest version of the slot type:

aws lex-models get-slot-type \


--region region \
--name FlowerTypes \
--slot-type-version "\$LATEST"

The response from Amazon Lex follows. Record the checksum for the current revision of the
$LATEST version.

{
"enumerationValues": [
{
"value": "tulips"
},
{
"value": "lilies"
},
{
"value": "roses"
}
],

91
Amazon Lex Developer Guide
Exercise 4: Publish a Version

"name": "FlowerTypes",
"checksum": "checksum",
"version": "$LATEST",
"lastUpdatedDate": timestamp,
"createdDate": timestamp,
"description": "Types of flowers to pick up"
}

2. Publish a version of the slot type. Use the checksum that you recorded in the previous step.

aws lex-models create-slot-type-version \


--region region \
--name FlowerTypes \
--checksum "checksum"

The response from Amazon Lex follows. Record the version number for the next step.

{
"version": "1",
"enumerationValues": [
{
"value": "tulips"
},
{
"value": "lilies"
},
{
"value": "roses"
}
],
"name": "FlowerTypes",
"createdDate": timestamp,
"lastUpdatedDate": timestamp,
"description": "Types of flowers to pick up"
}

Next Step
Step 2: Publish the Intent (AWS CLI) (p. 92)

Step 2: Publish the Intent (AWS CLI)


Before you can publish an intent, you have to publish all of the slot types referred to by the intent. The
slot types must be numbered versions, not the $LATEST version.

First, update the OrderFlowers intent to use the version of the FlowerTypes slot type that you
published in the previous step. Then publish a new version of the OrderFlowers intent.
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST and replace the backslash (\) continuation character at the end of
each line with a caret (^).

To publish a version of an intent (AWS CLI)

1. In the AWS CLI, get the $LATEST version of the OrderFlowers intent and save it to a file:

aws lex-models get-intent \


--region region \

92
Amazon Lex Developer Guide
Exercise 4: Publish a Version

--name OrderFlowers \
--intent-version "\$LATEST" > OrderFlowers_V4.json

2. In a text editor, open the OrderFlowers_V4.json file. Delete the createdDate,


lastUpdatedDate, and version fields. Find the FlowerTypes slot type and change the version
to the version number that you recorded in the previous step. The following fragment of the
OrderFlowers_V4.json file shows the location of the change:

{
"slotType": "FlowerTypes",
"name": "FlowerType",
"slotConstraint": "Required",
"valueElicitationPrompt": {
"maxAttempts": 2,
"messages": [
{
"content": "What type of flowers?",
"contentType": "PlainText"
}
]
},
"priority": 1,
"slotTypeVersion": "version",
"sampleUtterances": []
},

3. In the AWS CLI, save the revision of the intent:

aws lex-models put-intent \


--name OrderFlowers \
--cli-input-json file://OrderFlowers_V4.json

4. Get the checksum of the latest revision of the intent:

aws lex-models get-intent \


--region region \
--name OrderFlowers \
--intent-version "\$LATEST" > OrderFlowers_V4a.json

The following fragment of the response shows the checksum of the intent. Record this for the next
step.

"name": "OrderFlowers",
"checksum": "checksum",
"version": "$LATEST",

5. Publish a new version of the intent:

aws lex-models create-intent-version \


--region region \
--name OrderFlowers \
--checksum "checksum"

The following fragment of the response shows the new version of the intent. Record the version
number for the next step.

"name": "OrderFlowers",
"checksum": "checksum",
"version": "version",

93
Amazon Lex Developer Guide
Exercise 4: Publish a Version

Next Step
Step 3: Publish the Bot (AWS CLI) (p. 94)

Step 3: Publish the Bot (AWS CLI)


After you have published all of the slot types and intents that are used by your bot, you can publish the
bot.

Update the OrderFlowersBot bot to use the OrderFlowers intent that you updated in the previous
step. Then, publish a new version of the OrderFlowersBot bot.
Note
The following AWS CLI example is formatted for Unix, Linux, and macOS. For Windows, change
"\$LATEST" to $LATEST and replace the backslash (\) continuation character at the end of
each line with a caret (^).

To publish a version of a bot (AWS CLI)

1. In the AWS CLI, get the $LATEST version of the OrderFlowersBot bot and save it to a file:

aws lex-models get-bot \


--region region \
--name OrderFlowersBot \
--version-or-alias "\$LATEST" > OrderFlowersBot_V4.json

2. In a text editor, open the OrderFlowersBot_V4.json file. Delete the createdDate,


lastUpdatedDate, status and version fields. Find the OrderFlowers intent and change the
version to the version number that you recorded in the previous step. The following fragment of
OrderFlowersBot_V4.json shows the location of the change.

"intents": [
{
"intentVersion": "version",
"intentName": "OrderFlowers"
}

3. In the AWS CLI, save the new revision of the bot:

aws lex-models put-bot \


--name OrderFlowersBot \
--cli-input-json file://OrderFlowersBot_V4.json

4. Get the checksum of the latest revision of the bot:

aws lex-models get-bot \


--region region \
--name OrderFlowersBot > OrderFlowersBot_V4a.json

The following fragment of the response shows the checksum of the bot. Record this for the next
step.

"name": "OrderFlowersBot",
"locale": "en-US",
"checksum": "checksum",

5. Publish a new version of the bot:

aws lex-models create-bot-version \

94
Amazon Lex Developer Guide
Exercise 5: Create an Alias

--region region \
--name OrderFlowersBot \
--checksum "checksum"

The following fragment of the response shows the new version of the bot.

"checksum": "checksum",
"abortStatement": {
...
},
"version": "1",
"lastUpdatedDate": timestamp,

Next Step
Exercise 5: Create an Alias (AWS CLI) (p. 95)

Exercise 5: Create an Alias (AWS CLI)


An alias is a pointer to a specific version of a bot. With an alias you can easily update the version that
your client applications are using. For more information, see Versioning and Aliases (p. 97).To run the
commands in this exercise, you need to know the region where the commands will be run. For a list of
regions, see Model Building Limits (p. 187).

To create an alias (AWS CLI)

1. In the AWS CLI, get the version of the OrderFlowersBot bot that you created in Exercise 4: Publish
a Version (AWS CLI) (p. 91).

aws lex-models get-bot \


--region region \
--name OrderFlowersBot \
--version-or-alias version > OrderFlowersBot_V5.json

2. In a text editor, open OrderFlowersBot_v5.json. Find and record the version number.
3. In the AWS CLI, create the bot alias:

aws lex-models put-bot-alias \


--region region \
--name PROD \
--bot-name OrderFlowersBot \
--bot-version version

The following is the reponse from the server:

{
"name": "PROD",
"createdDate": timestamp,
"checksum": "checksum",
"lastUpdatedDate": timestamp,
"botName": "OrderFlowersBot",
"botVersion": "1"
}}

95
Amazon Lex Developer Guide
Exercise 6: Clean Up

Next Step
Exercise 6: Clean Up (AWS CLI) (p. 96)

Exercise 6: Clean Up (AWS CLI)


Delete the resources that you created and clean up your account.

You can delete only resources that are not in use. In general, you should delete resources in the following
order.

1. Delete aliases to free up bot resources.


2. Delete bots to free up intent resources.
3. Delete intents to free up slot type resources.
4. Delete slot types.

To run the commands in this exercise, you need to know the region where the commands will be run. For
a list of regions, see Model Building Limits (p. 187).

To clean up your account (AWS CLI)

1. In the AWS CLI command line, delete the alias:

aws lex-models delete-bot-alias \


--region region \
--name PROD \
--bot-name OrderFlowersBot

2. In the AWS CLI command line, delete the bot:

aws lex-models delete-bot \


--region region \
--name OrderFlowersBot

3. In the AWS CLI command line, delete the intent:

aws lex-models delete-intent \


--region region \
--name OrderFlowers

4. From the AWS CLI command line, delete the slot type:

aws lex-models delete-slot-type \


--region region \
--name FlowerTypes

You have removed all of the resources that you created and cleaned up your account.

96
Amazon Lex Developer Guide
Versioning

Versioning and Aliases


Amazon Lex supports publishing versions of bots, intents, and slot types so that you can control the
implementation that your client applications use. A version is a numbered snapshot of your work that
you can publish for use in different parts of your workflow, such as development, beta deployment, and
production.

Amazon Lex bots also support aliases. An alias is a pointer to a specific version of a bot. With an alias,
you can easily update the version that your client applications are using. For example, you can point an
alias to version 1 of your bot. When you are ready to update the bot, you publish version 2 and change
the alias to point to the new version. Because your applications use the alias instead of a specific version,
all of your clients get the new functionality without needing to be updated.

Topics
• Versioning (p. 97)
• Aliases (p. 99)

Versioning
When you version an Amazon Lex resource you create a snapshot of the resource so that you can use
the resource as it existed when the version was made. Once you've created a version it will stay the same
while you continue to work on your application.

The $LATEST Version


When you create an Amazon Lex bot, intent, or slot type there is only one version, the $LATEST version.

$LATEST is the working copy of your resource. You can update only the $LATEST version and until you
publish your first version, $LATEST is the only version of the resource that you have.

Only the $LATEST version of a resource can use the $LATEST version of another resource. For example,
the $LATEST version of a bot can use the $LATEST version of an intent, and the $LATEST version of an
intent can use the $LATEST version of a slot type.

Publishing an Amazon Lex Resource Version


When you publish a resource, Amazon Lex makes a copy of the $LATEST version and saves it as a
numbered version. The published version can't be changed.

97
Amazon Lex Developer Guide
Updating an Amazon Lex Resource

You create and publish versions using the Amazon Lex console or the CreateBotVersion (p. 205)
operation. For an example, see Exercise 3: Publish a Version and Create an Alias (p. 71).

When you modify the $LATEST version of a resource, you can publish the new version to make the
changes available to your client applications. Every time you publish a version, Amazon Lex copies the
$LATEST version to create the new version and increments the version number by 1. Version numbers
are never reused. For example, if you remove a resource numbered version 10 and then recreate it, the
next version number Amazon Lex assigns is version 11.

Before you can publish a bot, you must point it to a numbered version of any intent that it uses. If you
try to publish a new version of a bot that uses the $LATEST version of an intent, Amazon Lex returns an
HTTP 400 Bad Request exception. Before you can publish a numbered version of the intent, you must
point the intent to a numbered version of any slot type that it uses. Otherwise you will get an HTTP 400
Bad Request exception.

Note
Amazon Lex publishes a new version only if the last published version is different from the
$LATEST version. If you try to publish the $LATEST version without modifying it, Amazon Lex
doesn't create or publish a new version.

Updating an Amazon Lex Resource


You can update only the $LATEST version of an Amazon Lex bot, intent, or slot type. Published
versions can't be changed. You can publish a new version any time after you update a resource
in the console or with the CreateBotVersion (p. 205), the CreateIntentVersion (p. 210) or the
CreateSlotTypeVersion (p. 216) operations.

Deleting an Amazon Lex Resource or Version


Amazon Lex supports deleting a resource or version using the console or one of the API operations:

• DeleteBot (p. 220)


• DeleteBotVersion (p. 226)
• DeleteBotAlias (p. 222)

98
Amazon Lex Developer Guide
Aliases

• DeleteBotChannelAssociation (p. 224)


• DeleteIntent (p. 228)
• DeleteIntentVersion (p. 230)
• DeleteSlotType (p. 232)
• DeleteSlotTypeVersion (p. 234)

Aliases
An alias is a pointer to a specific version of an Amazon Lex bot. Use an alias to allow client applications
to use a specific version of the bot without requiring the application to track which version that is.

The following example shows two versions of an Amazon Lex bot, version $LATEST and version 1. Each
of these bot versions has an associated alias, DEV and PROD, respectively. Client applications use the
PROD alias to access the bot.

When you create a second version of the bot, you can update the alias to point to the new version of the
bot using the console or the PutBot (p. 297) operation. When you change the alias, all of your client
applications use the new version. If there is a problem with the new version, you can roll back to the
previous version by simply changing the alias to point to that version.

99
Amazon Lex Developer Guide
Aliases

Note
Although you can test the $LATEST version of a bot in the console, we recommend that when
you integrate a bot with your client application, you first publish a version and create an alias
that points to that version. Use the alias in your client application for the reasons explained in
this section. When you update an alias, Amazon Lex will wait until the session timeout of all
current sessions expires before it starts using the new version. For more information about the
session timeout, see the section called “Setting the Session Timeout” (p. 22)

100
Amazon Lex Developer Guide
Lambda Function Input Event and Response Format

Using Lambda Functions


You can create AWS Lambda functions to use as code hooks for your Amazon Lex bot. You can
identify Lambda functions to perform initialization and validation, fulfillment, or both in your intent
configuration.

We recommend that you use a Lambda function as a code hook for your bot. Without a Lambda
function, your bot returns the intent information to the client application for fulfillment.

Topics
• Lambda Function Input Event and Response Format (p. 101)
• Amazon Lex and AWS Lambda Blueprints (p. 108)

Lambda Function Input Event and Response


Format
This section describes the structure of the event data that Amazon Lex provides to a Lambda function.
Use this information to parse the input in your Lambda code. It also explains the format of the response
that Amazon Lex expects your Lambda function to return.

Topics
• Input Event Format (p. 101)
• Response Format (p. 104)

Input Event Format


The following shows the general format of an Amazon Lex event that is passed to a Lambda function.
Use this information when you are writing your Lambda function.
Note
The input format may change without a corresponding change in the messageVersion. Your
code should not throw an error if new fields are present.

{
"currentIntent": {
"name": "intent-name",
"slots": {
"slot name": "value",
"slot name": "value"
},
"slotDetails": {
"slot name": {
"resolutions" : [
{ "value": "resolved value" },
{ "value": "resolved value" }
],
"originalValue": "original text"

101
Amazon Lex Developer Guide
Input Event Format

},
"slot name": {
"resolutions" : [
{ "value": "resolved value" },
{ "value": "resolved value" }
],
"originalValue": "original text"
}
},
"confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)"
},
"bot": {
"name": "bot name",
"alias": "bot alias",
"version": "bot version"
},
"userId": "User ID specified in the POST request to Amazon Lex.",
"inputTranscript": "Text used to process the request",
"invocationSource": "FulfillmentCodeHook or DialogCodeHook",
"outputDialogMode": "Text or Voice, based on ContentType request header in runtime API
request",
"messageVersion": "1.0",
"sessionAttributes": {
"key": "value",
"key": "value"
},
"requestAttributes": {
"key": "value",
"key": "value"
}
}

Note the following additional information about the event fields:

• currentIntent – Provides the intent name, slots, slotDetails and confirmationStatus fields.

slots is a map of slot names, configured for the intent, to slot values that Amazon Lex has recognized
in the user conversation. A slot value remains null until the user provides a value.

The slot value in the input event may not match one of the values configured for the slot. For example,
if the user responds to the prompt "What color car would you like?" with "pizza," Amazon Lex will
return "pizza" as the slot value. Your function should validate the values to make sure that they make
sense in context.

slotDetails provides additional information about a slot value. The resolutions array contains a
list of additional values recognized for the slot. Each slot can have a maximum of five values.

The originalValue field contains the value that was entered by the user for the slot. When the slot
type is configured to return the top resolution value as the slot value, the originalValue may be
different from the value in the slots field.

confirmationStatus provides the user response to a confirmation prompt, if there is one. For
example, if Amazon Lex asks "Do you want to order a large cheese pizza?," depending on the user

102
Amazon Lex Developer Guide
Input Event Format

response, the value of this field can be Confirmed or Denied. Otherwise, this value of this field is
None.

If the user confirms the intent, Amazon Lex sets this field to Confirmed. If the user denies the intent,
Amazon Lex sets this value to Denied.

In the confirmation response, a user utterance might provide slot updates. For example, the user might
say "yes, change size to medium." In this case, the subsequent Lambda event has the updated slot
value, PizzaSize set to medium. Amazon Lex sets the confirmationStatus to None, because the
user modified some slot data, requiring the Lambda function to perform user data validation.

 
• bot – Information about the bot that processed the request.
• name – The name of the bot that processed the request.
• alias – The alias of the bot version that processed the request.
• version – The version of the bot that processed the request.

 
• userId – This value is provided by the client application. Amazon Lex passes it to the Lambda function.

 
• inputTranscript – The text used to process the request.

If the input was text, the inputTranscript field contains the text that was input by the user.

If the input was an audio stream, the inputTranscript field contains the text extracted from the
audio stream. This is the text that is actually processed to recognize intents and slot values.

 
• invocationSource – To indicate why Amazon Lex is invoking the Lambda function, it sets this to one of
the following values:
• DialogCodeHook – Amazon Lex sets this value to direct the Lambda function to initialize the
function and to validate the user's data input.

When the intent is configured to invoke a Lambda function as an initialization and validation code
hook, Amazon Lex invokes the specified Lambda function on each user input (utterance) after
Amazon Lex understands the intent.
Note
If the intent is not clear, Amazon Lex can't invoke the Lambda function.

 
• FulfillmentCodeHook – Amazon Lex sets this value to direct the Lambda function to fulfill an
intent.

If the intent is configured to invoke a Lambda function as a fulfillment code hook, Amazon Lex sets
the invocationSource to this value only 103after it has all the slot data to fulfill the intent.
Amazon Lex Developer Guide
Response Format

In your intent configuration, you can have two separate Lambda functions to initialize and validate
user data and to fulfill the intent. You can also use one Lambda function to do both. In that case, your
Lambda function can use the invocationSource value to follow the correct code path.

 
• outputDialogMode – For each user input, the client sends the request to Amazon Lex using one of
the runtime API operations, PostContent (p. 327) or PostText (p. 335). Amazon Lex use the request
parameters, Amazon Lex to determine whether the response to the client is text or voice, and sets this
field accordingly.

The Lambda function can use this information to generate an appropriate message. For example,
if the client expects a voice response, your Lambda function could return Speech Synthesis Markup
Language (SSML) instead of text.

 
• messageVersion – The version of the message that identifies the format of the event data going into
the Lambda function and the expected format of the response from a Lambda function.
Note
You configure this value when you define an intent. In the current implementation, only
message version 1.0 is supported. Therefore, the console assumes the default value of 1.0 and
doesn't show the message version.
• sessionAttributes – Application-specific session attributes that the client sends in the request. If you
want Amazon Lex to include them in the response to the client, your Lambda function should send
these back to Amazon Lex in the response. For more information, see Setting Session Attributes (p. 19)

 
• requestAttributes – request-specific attributes that the client sends in the request. Use request
attributes to pass information that doesn't need to persist for the entire session. For more information,
see Setting Request Attributes (p. 20)

Response Format
Amazon Lex expects a response from a Lambda function in the following format:

{
"sessionAttributes": {
"key1": "value1",
"key2": "value2"
...
},
"dialogAction": {
"type": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close",
Full structure based on the type field. See below for details.
}
}

The response consists of two fields. The sessionAttributes field is optional, the dialogAction
field is required. The contents of the dialogAction field depends on the value of the type field.For
details, see dialogAction (p. 105).

104
Amazon Lex Developer Guide
Response Format

sessionAttributes
Optional. If you include the sessionAttributes field it can be empty. If you want Amazon Lex to
include any session attributes in the response to the client application, your Lambda function must
return them in this field. For more information, see the PostContent (p. 327) and PostText (p. 335)
operations.

"sessionAttributes": {
"key1": "value1",
"key2": "value2"
}

dialogAction
Required. The dialogAction field directs Amazon Lex to the next course of action, and describes what
to expect from the user after Amazon Lex returns a response to the client.

The type field indicates the next course of action. It also determines the other fields that the Lambda
function needs to provide as part of the dialogAction value.

• Close — Informs Amazon Lex not to expect a response from the user. For example, "Your pizza order
has been placed" does not require a response.

The fulfillmentState field is required. Amazon Lex uses this value to set the dialogState field
in the PostContent (p. 327) or PostText (p. 335) response to the client application. The message
and responseCard fields are optional. If you don't specify a message, Amazon Lex uses the goodbye
message or the follow-up message configured for the intent.

"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled or Failed",
"message": {
"contentType": "PlainText or SSML or CustomPayload",
"content": "Message to convey to the user. For example, Thanks, your pizza has been
ordered."
},
"responseCard": {
"version": integer-value,
"contentType": "application/vnd.amazonaws.card.generic",
"genericAttachments": [
{
"title":"card-title",
"subTitle":"card-sub-title",
"imageUrl":"URL of the image to be shown",
"attachmentLinkUrl":"URL of the attachment to be associated with the card",
"buttons":[
{
"text":"button-text",
"value":"Value sent to server on button click"
}
]
}
]
}
}

• ConfirmIntent — Informs Amazon Lex that the user is expected to give a yes or no answer to
confirm or deny the current intent.

105
Amazon Lex Developer Guide
Response Format

You must include the intentName and slots fields. The slots field must contain an entry for each
of the slots configured for the specified intent. If the value of a slot is unknown, you must set it to null.
You must include the message field if the intent's confirmationPrompt field is null. If you specify
both the message field and the confirmationPrompt field, the response includes the contents of
the confirmationPrompt field. The responseCard field is optional.

"dialogAction": {
"type": "ConfirmIntent",
"message": {
"contentType": "PlainText or SSML or CustomPayload",
"content": "Message to convey to the user. For example, Are you sure you want a
large pizza?"
},
"intentName": "intent-name",
"slots": {
"slot-name": "value",
"slot-name": "value",
"slot-name": "value"
},
"responseCard": {
"version": integer-value,
"contentType": "application/vnd.amazonaws.card.generic",
"genericAttachments": [
{
"title":"card-title",
"subTitle":"card-sub-title",
"imageUrl":"URL of the image to be shown",
"attachmentLinkUrl":"URL of the attachment to be associated with the card",
"buttons":[
{
"text":"button-text",
"value":"Value sent to server on button click"
}
]
}
]
}
}

• Delegate — Directs Amazon Lex to choose the next course of action based on the bot configuration.
The response must include any session attributes, and the slots field must include all of the slots
specified for the requested intent. If the value of the field is unknown, you must set it to null. You will
get a DependencyFailedException exception if your fufillment function returns the Delegate
dialog action without removing any slots.

"dialogAction": {
"type": "Delegate",
"slots": {
"slot-name": "value",
"slot-name": "value",
"slot-name": "value"
}
}

• ElicitIntent — Informs Amazon Lex that the user is expected to respond with an utterance that
includes an intent. For example, "I want a large pizza," which indicates the OrderPizzaIntent. The
utterance "large," on the other hand, is not sufficient for Amazon Lex to infer the user's intent.

106
Amazon Lex Developer Guide
Response Format

The message and responseCard fields are optional. If you don't provide a message, Amazon Lex uses
one of the bot's clarification prompts.

{
"dialogAction": {
"type": "ElicitIntent",
"message": {
"contentType": "PlainText or SSML or CustomPayload",
"content": "Message to convey to the user. For example, What can I help you with?"
},
"responseCard": {
"version": integer-value,
"contentType": "application/vnd.amazonaws.card.generic",
"genericAttachments": [
{
"title":"card-title",
"subTitle":"card-sub-title",
"imageUrl":"URL of the image to be shown",
"attachmentLinkUrl":"URL of the attachment to be associated with the card",
"buttons":[
{
"text":"button-text",
"value":"Value sent to server on button click"
}
]
}
]
}
}

• ElicitSlot — Informs Amazon Lex that the user is expected to provide a slot value in the response.

The intentName, slotToElicit, and slots fields are required. The slots field must include all of
the slots specified for the requested intent. The message and responseCard fields are optional. If
you don't specify a message, Amazon Lex uses one of the slot elicitation prompts configured for the
slot.

"dialogAction": {
"type": "ElicitSlot",
"message": {
"contentType": "PlainText or SSML or CustomPayload",
"content": "Message to convey to the user. For example, What size pizza would you
like?"
},
"intentName": "intent-name",
"slots": {
"slot-name": "value",
"slot-name": "value",
"slot-name": "value"
},
"slotToElicit" : "slot-name",
"responseCard": {
"version": integer-value,
"contentType": "application/vnd.amazonaws.card.generic",
"genericAttachments": [
{
"title":"card-title",

107
Amazon Lex Developer Guide
Amazon Lex and AWS Lambda Blueprints

"subTitle":"card-sub-title",
"imageUrl":"URL of the image to be shown",
"attachmentLinkUrl":"URL of the attachment to be associated with the card",
"buttons":[
{
"text":"button-text",
"value":"Value sent to server on button click"
}
]
}
]
}
}

Amazon Lex and AWS Lambda Blueprints


The Amazon Lex console provides example bots (called bot blueprints) that are preconfigured so you can
quickly create and test a bot in the console. For each of these bot blueprints, Lambda function blueprints
are also provided. These blueprints provide sample code that works with their corresponding bots. You
can use these blueprints to quickly create a bot that is configured with a Lambda function as a code
hook, and test the end-to-end setup without having to write code.

You can use the following Amazon Lex bot blueprints and the corresponding AWS Lambda function
blueprints as code hooks for bots:

• Amazon Lex blueprint — OrderFlowers


• AWS Lambda blueprints — lex-order-flowers (Node.js code) and lex-order-flowers-
python
• Amazon Lex blueprint — ScheduleAppointment
• AWS Lambda blueprints — lex-make-appointment (Node.js code) and lex-make-
appointment-python
• Amazon Lex blueprint — BookTrip
• AWS Lambda blueprints — lex-book-trip (Node.js code) and lex-book-trip-python

To create a bot using a blueprint and configure it to use a Lambda function as a code hook, see
Exercise 1: Create an Amazon Lex Bot Using a Blueprint (Console) (p. 33). For an example of using other
blueprints, see Additional Examples: Creating Amazon Lex Bots (p. 130).

108
Amazon Lex Developer Guide
Deploying an Amazon Lex Bot on a Messaging Platform

Deploying Amazon Lex Bots


This section provides examples of deploying Amazon Lex bots on various messaging platforms and in
mobile applications.

Topics
• Deploying an Amazon Lex Bot on a Messaging Platform (p. 109)
• Deploying an Amazon Lex Bot in Mobile Applications (p. 123)

Deploying an Amazon Lex Bot on a Messaging


Platform
This section explains how to deploy Amazon Lex bots on the Facebook, Slack, and Twilio messaging
platforms.
Note
When storing your Facebook, Slack, or Twilio configurations, Amazon Lex uses AWS Key
Management Service customer master keys (CMK) to encrypt the information. The first time
that you create a channel to one of these messaging platforms, Amazon Lex creates a default
CMK (aws/lex). Alternatively, you can create your own CMK with AWS KMS. This gives you more
flexibility, including the ability to create, rotate, and disable keys. You can also define access
controls and audit the encryption keys used to protect your data. For more information, see the
AWS Key Management Service Developer Guide.

When a messaging platform sends a request to Amazon Lex it includes platform-specific information as
a request attribute to your Lambda function. Use these attributes to customize the way that your bot
behaves. For more information, see Setting Request Attributes (p. 20).

All of the attributes take the namespace, x-amz-lex:, as the prefix . For example, the user-id
attribute is called x-amz-lex:user-id. There are common attributes that are sent by all messaging
platforms in addition to attributes that are specific to a particular platform. The following tables list the
request attributes that messaging platforms send to your bot's Lambda function.

Common Request Attributes

Attribute Description

channel-id The channel endpoint identifier from Amazon Lex.

channel-name The channel name from Amazon Lex.

channel-type One of the following values:

• Facebook
• Kik
• Slack
• Twilio-SMS

109
Amazon Lex Developer Guide
Deploying an Amazon Lex Bot on a Messaging Platform

Attribute Description

webhook-endpoint-url The Amazon Lex endpoint for the channel.

Facebook Request Attributes

Attribute Description

user-id The Facebook identifier of the sender. See https://


developers.facebook.com/docs/messenger-platform/webhook-
reference/message-received.

facebook-page-id The Facebook page identifier of the recipient. See https://


developers.facebook.com/docs/messenger-platform/webhook-
reference/message-received.

Kik Request Attributes

Attribute Description

kik-chat-id The identifier for the conversation that your bot is involved in. For more
information, see https://dev.kik.com/#/docs/messaging#message-
formats.

kik-chat-type The type of conversation that the message originated from. For more
information, see https://dev.kik.com/#/docs/messaging#message-
formats.

kik-message-id A UUID the identifies the message. For more information, see https://
dev.kik.com/#/docs/messaging#message-formats.

kik-message-type The type of message. For more information, see https://dev.kik.com/#/


docs/messaging#message-types.

Twilio Request Attributes

Attribute Description

user-id The sender's phone number ("From"). See https://www.twilio.com/docs/


api/rest/message.

twilio-target-phone- The phone number of the recipient ("To"). See https://www.twilio.com/


number docs/api/rest/message.

Slack Request Attributes

Attribute Description

user-id The Slack user identifier. See https://api.slack.com/types/user.

slack-team-id The identifier of the team that sent the message. See https://
api.slack.com/methods/team.info.

slack-bot-token The developer token that gives the bot access to the Slack APIs. See
https://api.slack.com/docs/token-types.

110
Amazon Lex Developer Guide
Integrating with Facebook

Integrating an Amazon Lex Bot with Facebook


Messenger
Topics
• Step 1: Create an Amazon Lex Bot (p. 111)
• Step 2: Create a Facebook Application (p. 111)
• Step 3: Integrate Facebook Messenger with the Amazon Lex Bot (p. 111)
• Step 4: Test the Integration (p. 113)

This exercise shows how to integrate Facebook Messenger with your Amazon Lex bot. You perform the
following steps:

1. Create an Amazon Lex bot


2. Create a Facebook application
3. Integrate Facebook Messenger with your Amazon Lex bot
4. Validate the integration

Step 1: Create an Amazon Lex Bot


If you don't already have an Amazon Lex bot, create and deploy one. In this topic, we assume that
you are using the bot that you created in Getting Started Exercise 1. However, you can use any of the
example bots provided in this guide. For Getting Started Exercise 1, see Exercise 1: Create an Amazon Lex
Bot Using a Blueprint (Console) (p. 33).

1. Create an Amazon Lex bot. For instructions, see Exercise 1: Create an Amazon Lex Bot Using a
Blueprint (Console) (p. 33).
2. Deploy the bot and create an alias. For instructions, see Exercise 3: Publish a Version and Create an
Alias (p. 71).

Step 2: Create a Facebook Application


On the Facebook developer portal, create a Facebook application and a Facebook page. For instructions,
see Quick Start in the Facebook Messenger platform documentation. Write down the following:

• The App Secret for the Facebook App


• The Page Access Token for the Facebook page

Step 3: Integrate Facebook Messenger with the Amazon Lex Bot


In this section, you integrate Facebook Messenger with your Amazon Lex bot.

After you complete this step, the console provides a callback URL. Write down this URL.

To integrate Facebook Messenger with your bot

1. a. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
b. Choose your Amazon Lex bot.

111
Amazon Lex Developer Guide
Integrating with Facebook

c. Choose Channels.
d. Choose Facebook under Chatbots. The console displays the Facebook integration page.
e. On the Facebook integration page, do the following:

• Type the following name: BotFacebookAssociation.


• For KMS key, choose aws/lex .
• For Alias, choose the bot alias.
• For Verify token, type a token. This can be any string you choose (for example,
ExampleToken). You use this token later in the Facebook developer portal when you set up
the webhook.
• For Page access token, type the token that you obtained from Facebook in Step 2.
• For App secret key, type the key that you obtained from Facebook in Step 2.

f. Choose Activate.

The console creates the bot channel association and returns a callback URL. Write down this
URL.
2. On the Facebook developer portal, choose your app.
3. Choose the Messenger product, and choose Setup webhooks in the Webhooks section of the page.

For instructions, see Quick Start in the Facebook Messenger platform documentation.
4. On the webhook page of the subscription wizard, do the following:

• For Callback URL, type the callback URL provided in the Amazon Lex console earlier in the
procedure.
• For Verify Token, type the same token that you used in Amazon Lex.
• Choose Subscription Fields (messages, messaging_postbacks, and messaging_optins).
• Choose Verify and Save. This initiates a handshake between Facebook and Amazon Lex.
5. Enable Webhooks integration. Choose the page that you created, and then choose subscribe.
Note
If you update or recreate a webhook, unsubscribe and then resubscribe to the page.

112
Amazon Lex Developer Guide
Integrating with Kik

Step 4: Test the Integration


You can now start a conversation from Facebook Messenger with your Amazon Lex bot.

1. Open your Facebook page, and choose Message.


2. In the Messenger window, use the same test utterances provided in Step 1: Create an Amazon Lex
Bot (Console) (p. 35).

Integrating an Amazon Lex Bot with Kik


Topics
• Step 1: Create an Amazon Lex Bot (p. 113)
• Step 2: Create a Kik Bot (p. 113)
• Step 3: Integrate the Kik Bot with the Amazon Lex Bot (p. 114)
• Step 4: Test the Integration (p. 115)

This exercise provides instructions for integrating an Amazon Lex bot with the Kik messaging application.
You perform the following steps:

1. Create an Amazon Lex bot.


2. Create a Kik bot using the Kik app and website.
3. Integrate the your Amazon Lex bot with the Kik bot using the Amazon Lex console.
4. Engage in a conversation with your Amazon Lex bot using Kik to test the association between your
Amazon Lex bot and Kik.

Step 1: Create an Amazon Lex Bot


If you don't already have an Amazon Lex bot, create and deploy one. In this topic, we assume that
you are using the bot that you created in Getting Started Exercise 1. However, you can use any of the
example bots provided in this guide. For Getting Started Exercise 1, see Exercise 1: Create an Amazon Lex
Bot Using a Blueprint (Console) (p. 33)

1. Create an Amazon Lex bot. For instructions, see Exercise 1: Create an Amazon Lex Bot Using a
Blueprint (Console) (p. 33).
2. Deploy the bot and create an alias. For instructions, see Exercise 3: Publish a Version and Create an
Alias (p. 71).

Next Step

Step 2: Create a Kik Bot (p. 113)

Step 2: Create a Kik Bot


In this step you use the Kik user interface to create a Kik bot. You use information generated while
creating the bot to connect it to your Amazon Lex bot.

1. If you haven't already, download and install the Kik app and sign up for a Kik account. If you have an
account, log in.
2. Open the Kik website at https://dev.kik.com/. Leave the browser window open.
3. In the Kik app, choose the gear icon to open settings, and then choose Your Kik Code.

113
Amazon Lex Developer Guide
Integrating with Kik

4. Scan the Kik code on the Kik website to open the Botsworth chatbot. Choose Yes to open the Bot
Dashboard.
5. In the Kik app, choose Create a Bot. Follow the prompts to create your Kik bot.
6. Once the bot is created, choose Configuration in your browser. Make sure that your new bot is
selected.
7. Note the bot name and the API key for the next section.

Next Step

Step 3: Integrate the Kik Bot with the Amazon Lex Bot (p. 114)

Step 3: Integrate the Kik Bot with the Amazon Lex Bot
Now that you have created an Amazon Lex bot and a Kik bot, you are ready to create an channel
association between them in Amazon Lex. When the association is activated, Amazon Lex automatically
sets up a callback URL with Kik.

1. Sign in to the AWS Management Console, and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. Choose the Amazon Lex bot that you created in Step 1.
3. Choose the Channels tab.
4. In the Channels section, choose Kik.
5. On the Kik page, provide the following:

• Type a name. For example, BotKikIntegration.


• Type a description.
• Choose "aws/lex" from the KMS key drop-down.
• For Alias, choose an alias from the drop-down.
• For Kik bot user name, type the name that you gave the bot on Kik.
• For Kik API key, type the API key that was assigned to the bot on Kik.
• For User greeting, type the greeting that you would like your bot to send the first time that a user
chats with it.
• For Error message, enter an error message that is shown to the user when part of the
conversation is not understood.
• For Group chat behavior, choose one of the options:
• Enable – Enables the entire chat group to interact with your bot in a single conversation.
• Disable – Restricts the conversation to one user in the chat group.

114
Amazon Lex Developer Guide
Integrating with Kik

• Choose Activate to create the association and link it to the Kik bot.

Next Step

Step 4: Test the Integration (p. 115)

Step 4: Test the Integration


Now that you have created an association between your Amazon Lex bot and Kik, you can use the Kik
app to test the association.

1. Start the Kik app and log in. Select the bot that you created.
2. You can test the bot with the following:

115
Amazon Lex Developer Guide
Integrating with Slack

As you enter each phrase, your Amazon Lex bot will respond through Kik with the prompt that you
created for each slot.

Integrating an Amazon Lex Bot with Slack


Topics
• Step 1: Create an Amazon Lex Bot (p. 117)
• Step 2: Sign Up for Slack and Create a Slack Team (p. 117)
• Step 3: Create a Slack Application (p. 117)
• Step 4: Integrate the Slack Application with the Amazon Lex Bot (p. 118)
• Step 5: Complete Slack Integration (p. 119)
• Step 6: Test the Integration (p. 120)

This exercise provides instructions for integrating an Amazon Lex bot with the Slack messaging
application. You perform the following steps:

116
Amazon Lex Developer Guide
Integrating with Slack

1. Create an Amazon Lex bot.


2. Create a Slack messaging application.
3. Integrate the Slack application with your bot Amazon Lex.
4. Test the integration by engaging in conversation with your Amazon Lex bot. You send messages with
the Slack application and test in a browser window.

Step 1: Create an Amazon Lex Bot


If you don't already have an Amazon Lex bot, create and deploy one. In this topic, we assume that
you are using the bot that you created in Getting Started Exercise 1. However, you can use any of the
example bots provided in this guide. For Getting Started Exercise 1, see Exercise 1: Create an Amazon Lex
Bot Using a Blueprint (Console) (p. 33)

1. Create an Amazon Lex bot. For instructions, see Exercise 1: Create an Amazon Lex Bot Using a
Blueprint (Console) (p. 33).
2. Deploy the bot and create an alias. For instructions, see Exercise 3: Publish a Version and Create an
Alias (p. 71).

Next Step

Step 2: Sign Up for Slack and Create a Slack Team (p. 117)

Step 2: Sign Up for Slack and Create a Slack Team


Sign up for a Slack account and create a Slack team. For instructions, see Using Slack. In the next section,
you create a Slack application, which any Slack team can install.

Next Step

Step 3: Create a Slack Application (p. 117)

Step 3: Create a Slack Application


In this section, you do the following:

1. Create a Slack application on the Slack API Console


2. Configure the application to add the following features to your bot:
• A bot user
• Interactive messaging

At the end of this section, you get application credentials (Client Id, Client Secret, and Verification Token).
In the next section, you use this information to configure bot channel association in the Amazon Lex
console.

1. Sign in to the Slack API Console at http://api.slack.com .


2. Create an application.

After you have successfully created the application, Slack displays the Basic Information page for
the application.
3. Configure the application features as follows:

a. In the left menu, choose Bot Users.

117
Amazon Lex Developer Guide
Integrating with Slack

• Provide a user name.


• For Always Show My Bot as Online, choose On.
• To save the changes, choose Add Bot User.
b. In the left menu, choose Interactive Components.

• Choose Enable Interactive Components.


• In the Request URL box, specify any valid URL. For example, you can use https://
slack.com.
Note
For now, enter any valid URL to get the verification token that you need in the next
step. You will update this URL after you add the bot channel association in the
Amazon Lex console.
• Choose Enable Interactive Components.
4. In the left menu, in Settings, choose Basic Information. Record the following application
credentials:

• Client ID
• Client Secret
• Verification Token

Next Step

Step 4: Integrate the Slack Application with the Amazon Lex Bot (p. 118)

Step 4: Integrate the Slack Application with the Amazon Lex Bot
Now that you have Slack application credentials, you can integrate the application with your Amazon Lex
bot. To associate the Slack application with your bot, add a bot channel association in Amazon Lex.

In the Amazon Lex console, activate a bot channel association to associate the bot with your Slack
application. When the bot channel association is activated, Amazon Lex returns two URLs (Postback URL
and OAuth URL). Record these URLs because you need them later.

To integrate the Slack application with your Amazon Lex bot

1. Sign in to the AWS Management Console, and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. Choose the Amazon Lex bot that you created in Step 1.
3. Choose the Channels tab.
4. In the Chatbots section, choose Slack.
5. On the Slack page, provide the following:

• Type a name. For example, BotSlackIntegration.


• Choose "aws/lex" from the KMS key drop-down.
• For Alias, choose the bot alias.
• Type the Client Id, Client secret, and Verification Token, which you recorded in the preceding
step. These are the credentials of the Slack application.

118
Amazon Lex Developer Guide
Integrating with Slack

6. Choose Activate.

The console creates the bot channel association and returns two URLs (Postback URL and OAuth
URL). Record them. In the next section, you update your Slack application configuration to use these
endpoints as follows:

• The Postback URL is the Amazon Lex bot's endpoint that listens to Slack events. You use this URL:
• As the request URL in the Event Subscriptions feature of the Slack application.
• To replace the placeholder value for the request URL in the Interactive Messages feature of the
Slack application.
• The OAuth URL is your Amazon Lex bot's endpoint for an OAuth handshake with Slack.

Next Step

Step 5: Complete Slack Integration (p. 119)

Step 5: Complete Slack Integration


In this section, use the Slack API console to complete integration of the Slack application.

1. Sign in to the Slack API console at http://api.slack.com. Choose the app that you created in Step 3:
Create a Slack Application (p. 117).
2. Update the OAuth & Permissions feature as follows:

a. In the Redirect URLs section, add the OAuth URL that Amazon Lex provided in the preceding
step. Choose Add a new Redirect URL, and then choose Save URLs.
b. In the Scopes section, choose two permissions in the Select Permission Scopes drop-down.
Filter the list with the following text:

• chat:write:bot
• team:read

119
Amazon Lex Developer Guide
Integrating with Twilio SMS

Choose Save Changes.


3. Update the Interactive Components feature by updating the Request URL value to the Postback
URL that Amazon Lex provided in the preceding step. Choose Add, and then choose Save URLs.
4. Subscribe to the Event Subscriptions feature as follows:

• Enable events by choosing the On option.


• Set the Request URL value to the Postback URL that Amazon Lex provided in the preceding step.
• In the Subscribe to Bot Events section, subscribe to the message.im bot event to enable direct
messaging between the end user and the Slack bot.
• Save the changes.

Next Step

Step 6: Test the Integration (p. 120)

Step 6: Test the Integration


Now use a browser window to test the integration of Slack with your Amazon Lex bot.

1. Choose Manage Distribution under Settings. Choose Add to Slack to install the application.
Authorize the bot to respond to messsages.
2. You are redirected to your Slack team. In the left menu, in the Direct Messages section, choose your
bot. If you don't see your bot, choose the plus icon (+) next to Direct Messages to search for it.
3. Engage in a chat with your Slack application, which is linked to the Amazon Lex bot. Your bot now
responds to messages.

If you created the bot using Getting Started Exercise 1, you can use the example conversations
provided in that exercise. For more information, see Step 4: Add the Lambda Function as Code Hook
(Console) (p. 46).

Integrating an Amazon Lex Bot with Twilio


Programmable SMS
Topics
• Step 1: Create an Amazon Lex Bot (p. 121)
• Step 2: Create a Twilio SMS Account (p. 121)
• Step 3: Integrate the Twilio Messaging Service Endpoint with the Amazon Lex Bot (p. 121)
• Step 4: Test the Integration (p. 122)

This exercise provides instructions for integrating an Amazon Lex bot with the Twilio simple messaging
service (SMS). You perform the following steps:

1. Create an Amazon Lex bot


2. Integrate Twilio programmable SMS with your bot Amazon Lex
3. Engage in an interaction with the Amazon Lex bot by testing the setup using the SMS service on your
mobile phone
4. Test the integration

120
Amazon Lex Developer Guide
Integrating with Twilio SMS

Step 1: Create an Amazon Lex Bot


If you don't already have an Amazon Lex bot, create and deploy one. In this topic, we assume that
you are using the bot that you created in Getting Started Exercise 1. However, you can use any of the
example bots provided in this guide. For Getting Started Exercise 1, see Exercise 1: Create an Amazon Lex
Bot Using a Blueprint (Console) (p. 33).

1. Create an Amazon Lex bot. For instructions, see Exercise 1: Create an Amazon Lex Bot Using a
Blueprint (Console) (p. 33).
2. Deploy the bot and create an alias. For instructions, see Exercise 3: Publish a Version and Create an
Alias (p. 71).

Step 2: Create a Twilio SMS Account


Sign up for a Twilio account and record the following account information:

• ACCOUNT SID
• AUTH TOKEN

For sign-up instructions, see https://www.twilio.com/console.

Step 3: Integrate the Twilio Messaging Service Endpoint with


the Amazon Lex Bot
To integrate Twilio with your Amazon Lex bot

1. To associate the Amazon Lex bot with your Twilio programmable SMS endpoint, activate bot
channel association in the Amazon Lex console. When the bot channel association has been
activated, Amazon Lex returns a callback URL. Record this callback URL because you need it later.

a. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
b. Choose the Amazon Lex bot that you created in Step 1.
c. Choose the Channels tab.
d. In the Chatbots section, choose Twilio SMS.
e. On the Twilio SMS page, provide the following information:

• Type a name. For example, BotTwilioAssociation.


• Choose "aws/lex" from KMS key.
• For Alias, choose the bot alias.
• For Authentication Token, type the AUTH TOKEN for your Twilio account.
• For Account SID, type the ACCOUNT SID for your Twilio account.

121
Amazon Lex Developer Guide
Integrating with Twilio SMS

f. Choose Activate.

The console creates the bot channel association and returns a callback URL. Record this URL.
2. On the Twilio console, connect the Twilio SMS endpoint to the Amazon Lex bot.

a. Sign in to the Twilio console at https://www.twilio.com/console.


b. If you don't have a Twilio SMS endpoint, create it.
c. Update the Inbound Settings configuration of the messaging service by setting the REQUEST
URL value to the callback URL that Amazon Lex provided in the preceding step.

Step 4: Test the Integration


Use your mobile phone to test the integration between Twilio SMS and your bot.

To test integration

1. Sign in to the Twilio console at https://www.twilio.com/console and do the following:

a. Verify that you have a Twilio number associated with the messaging service under Manage
Numbers.

You send messages to this number and engage in SMS interaction with the Amazon Lex bot
from your mobile phone.
b. Verify that your mobile phone is whitelisted as Verified Caller ID.

If it isn't, follow instructions on the Twilio console to whitelist the mobile phone that you plan
to use for testing.

Now you can use your mobile phone to send messages to the Twilio SMS endpoint, which is
mapped to the Amazon Lex bot.
2. Using your mobile phone, send messages to the Twilio number.

122
Amazon Lex Developer Guide
Deploying an Amazon Lex Bot in Mobile Applications

The Amazon Lex bot responds. If you created the bot using Getting Started Exercise 1, you can use
the example conversations provided in that exercise. For more information, see Step 4: Add the
Lambda Function as Code Hook (Console) (p. 46).

Deploying an Amazon Lex Bot in Mobile


Applications
Using AWS SDKs, you can integrate your Amazon Lex bot with your mobile applications. For more
information, see Add Conversational Bots to Your Mobile App with Amazon Lex in the AWS Mobile
Developer Guide.

You can also use the AWS Mobile Hub to create a quickstart mobile app that demonstrates using the
Amazon Lex SDK in iOS and Android mobile applications. For more information, see AWS Mobile Hub
Conversational Bots.

123
Amazon Lex Developer Guide
Exporting and Importing in Amazon Lex Format

Importing and Exporting Amazon


Lex Bots, Intents, and Slot Types
You can import or export a bot, intent, or slot type. For example, if you want to share a bot with a
colleague in a different AWS account, you can export it, then send it to her. If you want to add multiple
utterances to a bot, you can export it, add the utterances, then import it back into your account.

You can export bots, intents, and slot types in either Amazon Lex (to share or modify them) or an Alexa
skill format. You can import only in Amazon Lex format.

When you export a resource, you have to export it in a format that is compatible with the service that
you are exporting to, Amazon Lex or the Alexa Skills Kit. If you export a bot in Amazon Lex format,
you can reimport it into your account, or an Amazon Lex user in another account can import it into his
account. You can also export a bot in a format compatible with an Alexa skill. Then you can import the
bot using the Alexa Skills Kit to make your bot available with Alexa. For more information, see Exporting
to an Alexa Skill (p. 128).

When you export a bot, intent or slot type, its resources are written to a JSON file. To export a bot,
intent, or slot type, you can use either the Amazon Lex console or the GetExport (p. 268) operation.
Import a bot, intent or slot type using the StartImport (p. 324).

Topics
• Exporting and Importing in Amazon Lex Format (p. 124)
• Exporting to an Alexa Skill (p. 128)

Exporting and Importing in Amazon Lex Format


To export bots, intents, and slot types, from Amazon Lex with the intention of reimporting into Amazon
Lex, you use create a JSON file in Amazon Lex format. You can edit your resources in this file and import
it back into Amazon Lex. For example, you can add utterances to an intent and then import the changed
intent back into your account. You can also use the JSON format to share a resource. For example, you
can export a bot from one AWS Region and then import it into another Region. Or you can send the
JSON file to a colleague to share a bot.

Topics
• Exporting in Amazon Lex Format (p. 124)
• Importing in Amazon Lex Format (p. 125)
• JSON Format for Importing and Exporting (p. 126)

Exporting in Amazon Lex Format


Export your Amazon Lex bots, intents, and slot types to a format that you can import to an AWS account.
You can export the following resources:

• A bot, including all of the intents and custom slot types used by the bot
• An intent, including all of the custom slot types used by the intent
• A custom slot type, including all of values for the slot type

124
Amazon Lex Developer Guide
Importing in Amazon Lex Format

You can export only a numbered version of a resource. You can't export a resource's $LATEST version.

Exporting is an asynchronous process. When the export is complete, you get an Amazon S3 presigned
URL. The URL provides the location of a .zip archive that contains the exported resource in JSON format.

You use either the console or the GetExport (p. 268) operation to export bots, intents, and custom slot
types.

The process for exporting, a bot, an intent, or a slot type is the same. In the following procedures,
substitute intent or slot type for bot.

Exporting a Bot
To export a bot

1. Sign in to the AWS Management Console, and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. Choose Bots, then choose the bot to export.
3. On the Actions menu, choose Export.
4. In the Export Bot dialog, choose the version of the bot to export. For Platform, choose Amazon Lex.
5. Choose Export.
6. Download and save the .zip archive.

Amazon Lex exports the bot to a JSON file that is contained in the .zip archive. To update the bot, modify
the JSON text, then import it back into Amazon Lex.

Next step

Importing in Amazon Lex Format (p. 125)

Importing in Amazon Lex Format


After you have exported a resource to a JSON file in the Amazon Lex format, you can import the JSON
file containing the resource into one or more AWS accounts. For example, you can export a bot, and then
import it into another AWS Region. Or you can send the bot to a colleague so that she can import it into
her account.

When you import a bot, intent, or slot type, you must decide whether you want to overwrite the
$LATEST version of a resource, such as an intent or a slot type, during import, or if you want the import
to fail if you want to preserve the resource that is in your account. For example, if you are uploading an
edited version of a resource to your account, you would choose to overwrite the $LATEST version. If you
are uploading a resource sent to you by a colleague, you can choose to have the import fail if there are
are resource conflicts so that your own resources aren't replaced.

When importing a resource, the permissions assigned to the user making the import request apply. The
user must have permissions for all of the resources in the account that the import affects. The user must
also have permission for the GetBot (p. 238), PutBot (p. 297), GetIntent (p. 274) PutIntent (p. 309),
GetSlotType (p. 285), PutSlotType (p. 319) operations. For more information about permissions, see
Using Identity-Based Policies (IAM Policies) for Amazon Lex (p. 196).

The import reports errors that occur during processing. Some errors are reported before the import
begins, others are reported during the import process. For example, if the account that is importing an
intent doesn't have permission to call a Lambda function that the intent uses, the import fails before
changes are made to the slot types or intents. If an import fails during the import process, the $LATEST
version of any intent or slot type imported before the process failed is modified. You can't roll back
changes made to the $LATEST version.

125
Amazon Lex Developer Guide
JSON Format for Importing and Exporting

When you import a resource, all dependent resources are imported to the $LATEST version of the
resource and then given a numbered version. For example, if a bot uses an intent, the intent is given a
numbered version. If an intent uses a custom slot type, the slot type is given a numbered version.

A resource is imported only once. For example, if the bot contains an OrderPizza intent and an
OrderDrink intent that both rely on the custom slot type Size, the Size slot type is imported once
and used for both intents.

The process for importing a bot, an intent, or a custom slot type is the same. In the following procedures,
substitute intent or slot type, as appropriate.

Importing a Bot
To import a bot

1. Sign in to the AWS Management Console, and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. Choose Bots, then choose the bot to import. To import a new bot, skip this step.
3. For Actions, choose Import.
4. For Import Bot, choose the .zip archive that contains the JSON file that contains the bot to import.
If you want to see merge conflicts before merging, choose Notify me of merge conflicts. If you turn
off conflict checking, the $LATEST version of all of the resources used by the bot are overwritten.
5. Choose Import. If you have chosen to be notified of merge conflicts and there are conflicts, a dialog
appears that lists them. To overwrite the $LASTEST version of all conflicting resources, choose
Overwrite and continue. To stop the import, choose Cancel.

You can now test the bot in your account.

JSON Format for Importing and Exporting


The following examples show the JSON structure for exporting and importing slot types, intents, and
bots in Amazon Lex format.

Slot Type structure


The following is the JSON structure for custom slot types. Use this structure when you import or export
slot types, and when you export intents that depend on custom slot types.

{
"metadata": {
"schemaVersion": "1.0",
"importType": "LEX",
"importFormat": "JSON"
},
"resource": {
"name": "slot type name",
"version": "version number",
"enumerationValues": [
{
"value": "enumeration value",
"synonyms": []
},
{
"value": "enumeration value",
"synonyms": []
}

126
Amazon Lex Developer Guide
JSON Format for Importing and Exporting

],
"valueSelectionStrategy": "ORIGINAL_VALUE or TOP_RESOLUTION"
}
}

Intent structure
The following is the JSON structure for intents. Use this structure when you import or export intents and
bots that depend on an intent.

{
"metadata": {
"schemaVersion": "1.0",
"importType": "LEX",
"importFormat": "JSON"
},
"resource": {
"description": "intent description",
"rejectionStatement": {
"messages": [
{
"contentType": "PlainText or SSML or CustomPayload",
"content": "string"
}
]
},
"name": "intent name",
"version": "version number",
"fulfillmentActivity": {
"type": "ReturnIntent or CodeHook"
},
"sampleUtterances": [
"string",
"string"
],
"slots": [
{
"name": "slot name",
"description": "slot description",
"slotConstraint": "Required or Optional",
"slotType": "slot type",
"valueElicitationPrompt": {
"messages": [
{
"contentType": "PlainText or SSML or CustomPayload",
"content": "string"
}
],
"maxAttempts": value
},
"priority": value,
"sampleUtterances": []
}
],
"confirmationPrompt": {
"messages": [
{
"contentType": "PlainText or SSML or CustomPayload",
"content": "string"
},
{
"contentType": "PlainText or SSML or CustomPayload",
"content": "string"
}

127
Amazon Lex Developer Guide
Exporting to an Alexa Skill

],
"maxAttempts": 2
},
"slotTypes": [
List of slot type JSON structures.
For more information, see Slot Type structure.
]
}
}

Bot structure
The following is the JSON structure for bots. Use this structure when you import or export bots.

{
"metadata": {
"schemaVersion": "1.0",
"importType": "LEX",
"importFormat": "JSON"
},
"resource": {
"name": "bot name",
"version": "version number",
"intents": [
List of intent JSON structures.
For more information, see Intent structure.
],
"slotTypes": [
List of slot type JSON structures.
For more information, see Slot Type structure.
],
"voiceId": "output voice ID",
"childDirected": boolean,
"locale": "en-US",
"idleSessionTTLInSeconds": timeout,
"description": "bot description",
"clarificationPrompt": {
"messages": [
{
"contentType": "PlainText or SSML or CustomPayload",
"content": "string"
}
],
"maxAttempts": value
},
"abortStatement": {
"messages": [
{
"contentType": "PlainText or SSML or CustomPayload",
"content": "string"
}
]
}
}
}

Exporting to an Alexa Skill


You can export your bot schema in a format compatible with an Alexa skill. After you export the bot to a
JSON file, you upload it to Alexa using the skill builder.

128
Amazon Lex Developer Guide
Exporting to an Alexa Skill

To export a bot and its schema (interaction model)

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. For Actions, choose Export.
3. Choose the name and version of the bot that you want to export. For the format, choose Alexa
Skills Kit, then choose Export.
4. When the download dialog box appears, choose a location to save the file, then choose Save.

The downloaded file is a .zip archive containing one file with the name of the exported bot. It contains
the information necessary to import the bot as an Alexa skill.
Note
Amazon Lex and the Alexa Skills Kit differ in the following ways:

• Session attributes, denoted by square brackets ([]), are not supported by the Alexa Skills Kit.
You need to update prompts that use session attributes.
• Punctuation marks are not supported by the Alexa Skills Kit. You need to update utterances
that use punctuation.

To upload the bot to an Alexa Skill

1. Log in to the developer portal at https://developer.amazon.com/.


2. To open the Alexa console, choose Developer Console, then choose ALEXA.
3. Open the Alexa Skill Kit page. In the Alexa Skills Kit box, choose Get Started.
4. Choose Add a New Skill. Fill in the required fields:

• Skill Type (choose Custom Interaction Model)


• Language
• Name
• Invocation Name
5. Choose Save, then choose Next.
6. Choose Launch Skill Builder.
7. On the left menu, choose Code Editor.
8. Extract the JSON file from the .zip archive that you downloaded. Paste the contents of the JSON file
into the code editor.
9. Choose Apply Changes, then choose Save Model.

After uploading the schema into the Alexa skill, make changes necessary for running the skill with Alexa.
For more information about creating an Alexa skill, see Use the Skill Builder (Beta) in the Alexa Skills Kit.

129
Amazon Lex Developer Guide
Example Bot: ScheduleAppointment

Additional Examples: Creating


Amazon Lex Bots
The following sections provide additional Amazon Lex exercises with step-by-step instructions.

Topics
• Example Bot: ScheduleAppointment (p. 130)
• Example Bot: BookTrip (p. 148)
• Example: Using a Response Card (p. 170)
• Example: Updating Utterances (p. 173)
• Example: Integrating with a Web site (p. 174)

Example Bot: ScheduleAppointment


The example bot in this exercise schedules appointments for a dentist's office. The example also
illustrates using response cards to obtain user input with buttons. Specifically, the example illustrates
generating response cards dynamically at runtime.

You can configure response cards at build time (also referred to as static response cards) or generate
them dynamically in an AWS Lambda function. In this example, the bot uses the following response
cards:

• A response card that lists buttons for appointment type. For example:

• A response card that lists buttons for appointment date. For example:

130
Amazon Lex Developer Guide
Example Bot: ScheduleAppointment

• A response card that lists buttons to confirm a suggested appointment time. For example:

The available appointment dates and times vary, which requires you to generate response cards at
runtime. You use an AWS Lambda function to generate these response cards dynamically. The Lambda
function returns response cards in its response to Amazon Lex. Amazon Lex includes the response card in
its response to the client.

If a client (for example, Facebook Messenger) supports response cards, the user can either choose from
the list of buttons or type the response. Otherwise, the user simply types the response.

In addition to the button shown in the preceding example, you can also include images, attachments,
and other useful information to display on response cards. For information about response cards, see
Response Cards (p. 15).

In this exercise, you do the following:

• Create and test a bot (using the ScheduleAppointment blueprint). For this exercise, you use a bot
blueprint to quickly set up and test the bot. For a list of available blueprints, see Amazon Lex and AWS
Lambda Blueprints (p. 108).This bot is preconfigured with one intent (MakeAppointment).

 
• Create and test a Lambda function (using the lex-make-appointment-python blueprint provided by
Lambda). You configure the MakeAppointment intent to use this Lambda function as a code hook to
perform initialization, validation, and fulfillment tasks.
Note
The provided example Lambda function showcases a dynamic conversation based on the
mocked-up availability of a dentist appointment. In a real application, you might use a real
calendar to set an appointment.
• Update the MakeAppointment intent configuration to use the Lambda function as a code hook. Then,
test the end-to-end experience.

131
Amazon Lex Developer Guide
Overview of the Bot Blueprint (ScheduleAppointment)

• Publish the schedule appointment bot to Facebook Messenger so you can see the response cards in
action (the client in the Amazon Lex console currently does not support response cards).

The following sections provide summary information about the blueprints you use in this exercise.

Topics
• Overview of the Bot Blueprint (ScheduleAppointment) (p. 132)
• Overview of the Lambda Function Blueprint (lex-make-appointment-python) (p. 133)
• Step 1: Create an Amazon Lex Bot (p. 133)
• Step 2: Create a Lambda Function (p. 135)
• Step 3: Update the Intent: Configure a Code Hook (p. 135)
• Step 4: Deploy the Bot on the Facebook Messenger Platform (p. 136)
• Details of Information Flow (p. 137)

Overview of the Bot Blueprint


(ScheduleAppointment)
The ScheduleAppointment blueprint that you use to create a bot for this exercise is preconfigured with
the following:

• Slot types – One custom slot type called AppointmentTypeValue, with the enumeration values
root canal, cleaning, and whitening.
• Intent – One intent (MakeAppointment), which is preconfigured as follows:
• Slots – The intent is configured with the following slots:
• Slot AppointmentType, of the AppointmentTypes custom type.
• Slot Date, of the AMAZON.DATE built-in type.
• Slot Time, of the AMAZON.TIME built-in type.
• Utterances – The intent is preconfigured with the following utterances:
• "I would like to book an appointment"
• "Book an appointment"
• "Book a {AppointmentType}"

If the user utters any of these, Amazon Lex determines that MakeAppointment is the intent, and
then uses the prompts to elicit slot data.
• Prompts – The intent is preconfigured with the following prompts:
• Prompt for the AppointmentType slot – "What type of appointment would you like to schedule?"
• Prompt for the Date slot – "When should I schedule your {AppointmentType}?"
• Prompt for the Time slot – "At what time do you want to schedule the {AppointmentType}?" and

"At what time on {Date}?"


• Confirmation prompt – "{Time} is available, should I go ahead and book your appointment?"
• Cancel message– "Okay, I will not schedule an appointment."

132
Amazon Lex Developer Guide
Overview of the Lambda Function
Blueprint (lex-make-appointment-python)

Overview of the Lambda Function Blueprint (lex-


make-appointment-python)
The Lambda function blueprint (lex-make-appointment-python) is a code hook for bots that you create
using the ScheduleAppointment bot blueprint.

This Lambda function blueprint code can perform both initialization/validation and fulfillment tasks.

• The Lambda function code showcases a dynamic conversation that is based on example availability for
a dentist appointment (in real applications, you might use a calendar). For the day or date that the user
specifies, the code is configured as follows:
• If there are no appointments available, the Lambda function returns a response directing
Amazon Lex to prompt the user for another day or date (by setting the dialogAction type to
ElicitSlot). For more information, see Response Format (p. 104).
• If there is only one appointment available on the specified day or date, the Lambda function
suggests the available time in the response and directs Amazon Lex to obtain user confirmation
by setting the dialogAction in the response to ConfirmIntent. This illustrates how you can
improve the user experience by proactively suggesting the available time for an appointment.
• If there are multiple appointments available, the Lambda function returns a list of available times in
the response to Amazon Lex. Amazon Lex returns a response to the client with the message from the
Lambda function.
• As the fulfillment code hook, the Lambda function returns a summary message indicating that an
appointment is scheduled (that is, the intent is fulfilled).

Note
In this example, we show how to use response cards. The Lambda function constructs and
returns a response card to Amazon Lex. The response card lists available days and times
as buttons to choose from. When testing the bot using the client provided by the Amazon
Lex console, you cannot see the response card. To see it, you must integrate the bot with a
messaging platform, such as Facebook Messenger. For instructions, see Integrating an Amazon
Lex Bot with Facebook Messenger (p. 111). For more information about response cards, see
Managing Messages (p. 9).

When Amazon Lex invokes the Lambda function, it passes event data as input. One of the event fields
is invocationSource, which the Lambda function uses to choose between an input validation and
fulfillment activity. For more information, see Input Event Format (p. 101).

Next Step

Step 1: Create an Amazon Lex Bot (p. 133)

Step 1: Create an Amazon Lex Bot


In this section, you create an Amazon Lex bot using the ScheduleAppointment blueprint, which is
provided in the Amazon Lex console.

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. On the Bots page, choose Create.
3. On the Create your Lex bot page, do the following:

• Choose the ScheduleAppointment blueprint.


• Leave the default bot name (ScheduleAppointment).

133
Amazon Lex Developer Guide
Step 1: Create an Amazon Lex Bot

4. Choose Create.

This step saves and builds the bot. The console sends the following requests to Amazon Lex during
the build process:

• Create a new version of the slot types (from the $LATEST version). For information
about slot types defined in this bot blueprint, see Overview of the Bot Blueprint
(ScheduleAppointment) (p. 132).
• Create a version of the MakeAppointment intent (from the $LATEST version). In some cases, the
console sends a request for the update API operation before creating a new version.
• Update the $LATEST version of the bot.

At this time, Amazon Lex builds a machine learning model for the bot. When you test the bot in
the console, the console uses the runtime API to send user input back to Amazon Lex. Amazon Lex
then uses the machine learning model to interpret the user input.
5. The console shows the ScheduleAppointment bot. On the Editor tab, review the preconfigured
intent (MakeAppointment) details.
6. Test the bot in the test window. Use the following screen shot to engage in a test conversation with
your bot:

Note the following:

• From the initial user input ("Book an appointment"), the bot infers the intent
(MakeAppointment).
• The bot then uses the configured prompts to get slot data from the user.
• The bot blueprint has the MakeAppointment intent configured with the following confirmation
prompt:

134
Amazon Lex Developer Guide
Step 2: Create a Lambda Function

{Time} is available, should I go ahead and book your appointment?

After the user provides all of the slot data, Amazon Lex returns a response to the client with a
confirmation prompt as the message. The client displays the message for the user:

16:00 is available, should I go ahead and book your appointment?

Notice that the bot accepts any appointment date and time values because you don't have any code
to initialize or validate the user data. In the next section, you add a Lambda function to do this.

Next Step

Step 2: Create a Lambda Function (p. 135)

Step 2: Create a Lambda Function


In this section, you create a Lambda function using a blueprint (lex-make-appointment-python) that is
provided in the Lambda console. You also test the Lambda function by invoking it using sample Amazon
Lex event data that is provided by the console.

1. Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2. Choose Create a Lambda function.
3. For Select blueprint, type lex to find the blueprint, and then choose the lex-make-appointment-
python blueprint.
4. Configure the Lambda function as follows, and then choose Create Function.

• Type the Lambda function name (MakeAppointmentCodeHook).


• For the role, choose Create a new role from template(s), and then type a role name.
• Leave other default values.
5. Test the Lambda function.

a. Choose Actions, and then chooseConfigure test event.


b. From the Sample event template list, choose Lex-Make Appointment (preview). This sample
event uses the Amazon Lex request/response model, with values set to match a request from
your Amazon Lex bot. For information about the Amazon Lex request/response model, see
Using Lambda Functions (p. 101).
c. Choose Save and test.
d. Verify that the Lambda function successfully executed. The response in this case matches the
Amazon Lex response model.

Next Step

Step 3: Update the Intent: Configure a Code Hook (p. 135)

Step 3: Update the Intent: Configure a Code Hook


In this section, you update the configuration of the MakeAppointment intent to use the Lambda
function as a code hook for the validation and fulfillment activities.

135
Amazon Lex Developer Guide
Step 4: Deploy the Bot on the
Facebook Messenger Platform

1. In the Amazon Lex console, select the ScheduleAppointment bot. The console shows the
MakeAppointment intent. Modify the intent configuration as follows.
Note
You can update only the $LATEST versions of any of the Amazon Lex resources, including
the intents. Make sure that the intent version is set to $LATEST. You have not published a
version of your bot yet, so it should still be the $LATEST version in the console.

a. In the Options section, choose Initialization and validation code hook, and then choose the
Lambda function from the list.
b. In the Fulfillment section, choose AWS Lambda function, and then choose the Lambda
function from the list.
c. Choose Goodbye message, and type a message.
2. Choose Save, and then choose Build.
3. Test the bot.

Next Step

Step 4: Deploy the Bot on the Facebook Messenger Platform (p. 136)

Step 4: Deploy the Bot on the Facebook Messenger


Platform
In the preceding section, you tested the ScheduleAppointment bot using the client in the Amazon Lex
console. Currently, the Amazon Lex console does not support response cards. To test the dynamically

136
Amazon Lex Developer Guide
Details of Information Flow

generated response cards that the bot supports, deploy the bot on the Facebook Messenger platform
and test it.

For instructions, see Integrating an Amazon Lex Bot with Facebook Messenger (p. 111).

Next Step

Details of Information Flow (p. 137)

Details of Information Flow


The ScheduleAppointment bot blueprint primarily showcases the use of dynamically generated
response cards. The Lambda function in this exercise includes response cards in its response to Amazon
Lex. Amazon Lex includes the response cards in its reply to the client. This section explains both the
following:

• Data flow between client and Amazon Lex.

The section assumes client sends requests to Amazon Lex using the PostText runtime API and shows
request/response details accordingly. For more information about the PostText runtime API, see
PostText (p. 335).
Note
For an example of information flow between client and Amazon Lex in which client uses the
PostContent API, see Step 2a (Optional): Review the Details of the Spoken Information Flow
(Console) (p. 37).

 
• Data flow between Amazon Lex and the Lamba function. For more information, see Lambda Function
Input Event and Response Format (p. 101).

Note
The example assumes that you are using the Facebook Messenger client, which does not pass
session attributes in the request to Amazon Lex. Accordingly, the example requests shown in this
section show empty sessionAttributes. If you test the bot using the client provided in the
Amazon Lex console, the client includes the session attributes.

This section describes what happens after each user input.

1. User: Types Book an appointment.

a. The client (console) sends the following PostContent (p. 327) request to Amazon Lex:

POST /bot/ScheduleAppointment/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/
text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"book appointment",
"sessionAttributes":{}
}

Both the request URI and the body provide information to Amazon Lex:

137
Amazon Lex Developer Guide
Details of Information Flow

• Request URI – Provides the bot name (ScheduleAppointment), the bot alias ($LATEST), and
the user name ID. The trailing text indicates that it is a PostText (not PostContent) API
request.
• Request body – Includes the user input (inputText) and empty sessionAttributes.
b. From the inputText, Amazon Lex detects the intent (MakeAppointment). The service
invokes the Lambda function, which is configured as a code hook, to perform initialization and
validation by passing the following event. For details, see Input Event Format (p. 101).

{
"currentIntent": {
"slots": {
"AppointmentType": null,
"Date": null,
"Time": null
},
"name": "MakeAppointment",
"confirmationStatus": "None"
},
"bot": {
"alias": null,
"version": "$LATEST",
"name": "ScheduleAppointment"
},
"userId": "bijt6rovckwecnzesbthrr1d7lv3ja3n",
"invocationSource": "DialogCodeHook",
"outputDialogMode": "Text",
"messageVersion": "1.0",
"sessionAttributes": {}
}

In addition to the information sent by the client, Amazon Lex also includes the following data:

• currentIntent – Provides current intent information.


• invocationSource – Indicates the purpose of the Lambda function invocation. In this case,
the purpose is to perform user data initialization and validation. (Amazon Lex knows that the
user has not provided all of the slot data to fulfill the intent yet.)
• messageVersion – Currently Amazon Lex supports only the 1.0 version.
c. At this time, all of the slot values are null (there is nothing to validate). The Lambda function
returns the following response to Amazon Lex, directing the service to elicit information
for the AppointmentType slot. For information about the response format, see Response
Format (p. 104).

{
"dialogAction": {
"slotToElicit": "AppointmentType",
"intentName": "MakeAppointment",
"responseCard": {
"genericAttachments": [
{
"buttons": [
{
"text": "cleaning (30 min)",
"value": "cleaning"
},
{
"text": "root canal (60 min)",
"value": "root canal"
},
{

138
Amazon Lex Developer Guide
Details of Information Flow

"text": "whitening (30 min)",


"value": "whitening"
}
],
"subTitle": "What type of appointment would you like to
schedule?",
"title": "Specify Appointment Type"
}
],
"version": 1,
"contentType": "application/vnd.amazonaws.card.generic"
},
"slots": {
"AppointmentType": null,
"Date": null,
"Time": null
},
"type": "ElicitSlot",
"message": {
"content": "What type of appointment would you like to schedule?",
"contentType": "PlainText"
}
},
"sessionAttributes": {}
}

The response includes the dialogAction and sessionAttributes fields. Among other
things, the dialogAction field returns the following fields:

• type – By setting this field to ElicitSlot, the Lambda function directs Amazon Lex to
elicit the value for the slot specified in the slotToElicit field. The Lambda function also
provides a message to convey to the user.
• responseCard – Identifies a list of possible values for the AppointmentType slot. A client
that supports response cards (for example, the Facebook Messenger) displays a response card
to allow the user to choose an appointment type, as follows:

d. As indicated by the dialogAction.type in the response from the Lambda function, Amazon
Lex sends the following response back to the client:

139
Amazon Lex Developer Guide
Details of Information Flow

The client reads the response, and then displays the message: "What type of appointment
would you like to schedule?" and the response card (if the client supports response cards).
2. User: Depending on the client, the user has two options:

• If the response card is shown, choose root canal (60 min) or type root canal.
• If the client does not support response cards, type root canal.

a. The client sends the following PostText request to Amazon Lex (line breaks have been added
for readability):

POST /bot/BookTrip/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "root canal",
"sessionAttributes": {}
}

b. Amazon Lex invokes the Lambda function for user data validation by sending the following
event as a parameter:

{
"currentIntent": {
"slots": {
"AppointmentType": "root canal",
"Date": null,
"Time": null
},
"name": "MakeAppointment",
"confirmationStatus": "None"
},
"bot": {
"alias": null,
"version": "$LATEST",
"name": "ScheduleAppointment"
},
"userId": "bijt6rovckwecnzesbthrr1d7lv3ja3n",
"invocationSource": "DialogCodeHook",
"outputDialogMode": "Text",
"messageVersion": "1.0",

140
Amazon Lex Developer Guide
Details of Information Flow

"sessionAttributes": {}
}

In the event data, note the following:

• invocationSource continues to be DialogCodeHook. In this step, we are just validating


user data.
• Amazon Lex sets the AppointmentType field in the currentIntent.slots slot to root
canal.
• Amazon Lex simply passes the sessionAttributes field between the client and the
Lambda function.
c. The Lambda function validates the user input and returns the following response to Amazon
Lex, directing the service to elicit a value for the appointment date.

{
"dialogAction": {
"slotToElicit": "Date",
"intentName": "MakeAppointment",
"responseCard": {
"genericAttachments": [
{
"buttons": [
{
"text": "2-15 (Wed)",
"value": "Wednesday, February 15, 2017"
},
{
"text": "2-16 (Thu)",
"value": "Thursday, February 16, 2017"
},
{
"text": "2-17 (Fri)",
"value": "Friday, February 17, 2017"
},
{
"text": "2-20 (Mon)",
"value": "Monday, February 20, 2017"
},
{
"text": "2-21 (Tue)",
"value": "Tuesday, February 21, 2017"
}
],
"subTitle": "When would you like to schedule your root canal?",
"title": "Specify Date"
}
],
"version": 1,
"contentType": "application/vnd.amazonaws.card.generic"
},
"slots": {
"AppointmentType": "root canal",
"Date": null,
"Time": null
},
"type": "ElicitSlot",
"message": {
"content": "When would you like to schedule your root canal?",
"contentType": "PlainText"
}
},
"sessionAttributes": {}

141
Amazon Lex Developer Guide
Details of Information Flow

Again, the response includes the dialogAction and sessionAttributes fields. Among
other things, the dialogAction field returns the following fields:

• type – By setting this field to ElicitSlot, the Lambda function directs Amazon Lex to
elicit the value for the slot specified in the slotToElicit field. The Lambda function also
provides a message to convey to the user.
• responseCard – Identifies a list of possible values for the Date slot. A client that supports
response cards (for example, Facebook Messenger) displays a response card that allows the
user to choose an appointment date:

Although the Lambda function returned five dates, the client (Facebook Messenger) has a
limit of three buttons for a response card. Therefore, you see only the first three values in the
screen shot.

These dates are hard coded in the Lambda function. In a production application, you might
use a calendar to get available dates in real time. Because the dates are dynamic, you must
generate the response card dynamically in the Lambda function.
d. Amazon Lex notices the dialogAction.type and returns a response to the client that includes
information from the Lambda function's response.

The client displays the message: When would you like to schedule your root canal? and the
response card (if the client supports response cards).
3. User: Types Thursday.

142
Amazon Lex Developer Guide
Details of Information Flow

a. The client sends the following PostText request to Amazon Lex (line breaks have been added
for readability):

POST /bot/BookTrip/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "Thursday",
"sessionAttributes": {}
}

b. Amazon Lex invokes the Lambda function for user data validation by sending in the following
event as a parameter:

{
"currentIntent": {
"slots": {
"AppointmentType": "root canal",
"Date": "2017-02-16",
"Time": null
},
"name": "MakeAppointment",
"confirmationStatus": "None"
},
"bot": {
"alias": null,
"version": "$LATEST",
"name": "ScheduleAppointment"
},
"userId": "u3fpr9gghj02zts7y5tpq5mm4din2xqy",
"invocationSource": "DialogCodeHook",
"outputDialogMode": "Text",
"messageVersion": "1.0",
"sessionAttributes": {}
}

In the event data, note the following:

• invocationSource continues to be DialogCodeHook. In this step, we are just validating


the user data.
• Amazon Lex sets the Date field in the currentIntent.slots slot to 2017-02-16.
• Amazon Lex simply passes the sessionAttributes between the client and the Lambda
function.
c. The Lambda function validates the user input. This time the Lambda function determines that
there are no appointments available on the specified date. It returns the following response to
Amazon Lex, directing the service to again elicit a value for the appointment date.

{
"dialogAction": {
"slotToElicit": "Date",
"intentName": "MakeAppointment",
"responseCard": {
"genericAttachments": [
{
"buttons": [
{
"text": "2-15 (Wed)",
"value": "Wednesday, February 15, 2017"
},

143
Amazon Lex Developer Guide
Details of Information Flow

{
"text": "2-17 (Fri)",
"value": "Friday, February 17, 2017"
},
{
"text": "2-20 (Mon)",
"value": "Monday, February 20, 2017"
},
{
"text": "2-21 (Tue)",
"value": "Tuesday, February 21, 2017"
}
],
"subTitle": "When would you like to schedule your root canal?",
"title": "Specify Date"
}
],
"version": 1,
"contentType": "application/vnd.amazonaws.card.generic"
},
"slots": {
"AppointmentType": "root canal",
"Date": null,
"Time": null
},
"type": "ElicitSlot",
"message": {
"content": "We do not have any availability on that date, is there
another day which works for you?",
"contentType": "PlainText"
}
},
"sessionAttributes": {
"bookingMap": "{\"2017-02-16\": []}"
}
}

Again, the response includes the dialogAction and sessionAttributes fields. Among
other things, the dialogAction returns the following fields:

• dialogAction field:
• type – The Lambda function sets this value to ElicitSlot and resets the slotToElicit
field to Date. The Lambda function also provides an appropriate message to convey to the
user.
• responseCard – Returns a list of values for the Date slot.
• sessionAttributes - This time the Lambda function includes the bookingMap session
attribute. Its value is the requested date of the appointment and available appointments (an
empty object indicates that no appointments are available).
d. Amazon Lex notices the dialogAction.type and returns a response to the client that includes
information from the Lambda function's response.

144
Amazon Lex Developer Guide
Details of Information Flow

The client displays the message: We do not have any availability on that date, is there another
day which works for you? and the response card (if the client supports response cards).
4. User: Depending on the client, the user has two options:

• If the response card is shown, choose 2-15 (Wed) or type Wednesday.


• If the client does not support response cards, type Wednesday.

a. The client sends the following PostText request to Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText": "Wednesday",
"sessionAttributes": {
}
}

Note
The Facebook Messenger client does not set any session attributes. If you want to
maintain session states between requests, you must do so in the Lambda function. In
a real application, you might need to maintain these session attributes in a backend
database.
b. Amazon Lex invokes the Lambda function for user data validation by sending the following
event as a parameter:

{
"currentIntent": {
"slots": {
"AppointmentType": "root canal",
"Date": "2017-02-15",
"Time": null
},
"name": "MakeAppointment",
"confirmationStatus": "None"
},
"bot": {

145
Amazon Lex Developer Guide
Details of Information Flow

"alias": null,
"version": "$LATEST",
"name": "ScheduleAppointment"
},
"userId": "u3fpr9gghj02zts7y5tpq5mm4din2xqy",
"invocationSource": "DialogCodeHook",
"outputDialogMode": "Text",
"messageVersion": "1.0",
"sessionAttributes": {
}
}

Amazon Lex updated currentIntent.slots by setting the Date slot to 2017-02-15.


c. The Lambda function validates the user input and returns the following response to Amazon
Lex, directing it to elicit the value for the appointment time.

{
"dialogAction": {
"slots": {
"AppointmentType": "root canal",
"Date": "2017-02-15",
"Time": "16:00"
},
"message": {
"content": "What time on 2017-02-15 works for you? 4:00 p.m. is our
only availability, does that work for you?",
"contentType": "PlainText"
},
"type": "ConfirmIntent",
"intentName": "MakeAppointment",
"responseCard": {
"genericAttachments": [
{
"buttons": [
{
"text": "yes",
"value": "yes"
},
{
"text": "no",
"value": "no"
}
],
"subTitle": "Is 4:00 p.m. on 2017-02-15 okay?",
"title": "Confirm Appointment"
}
],
"version": 1,
"contentType": "application/vnd.amazonaws.card.generic"
}
},
"sessionAttributes": {
"bookingMap": "{\"2017-02-15\": [\"10:00\", \"16:00\", \"16:30\"]}"
}
}

Again, the response includes the dialogAction and sessionAttributes fields. Among
other things, the dialogAction returns the following fields:

• dialogAction field:
• type – The Lambda function sets this value to ConfirmIntent, directing Amazon Lex to
obtain user confirmation of the appointment time suggested in the message.

146
Amazon Lex Developer Guide
Details of Information Flow

• responseCard – Returns a list of yes/no values for the user to choose from. If the client
supports response cards, it displays the response card, as shown in the following example:

• sessionAttributes - The Lambda function sets the bookingMap session attribute with its
value set to the appointment date and available appointments on that date. In this example,
these are 30-minute appointments. For a root canal that requires one hour, only 4 p.m. can be
booked.
d. As indicated in the dialogAction.type in the Lambda function's response, Amazon Lex
returns the following response to the client:

The client displays the message: What time on 2017-02-15 works for you? 4:00 p.m. is our
only availability, does that work for you?
5. User: Choose yes.

Amazon Lex invokes the Lambda function with the following event data. Because the user replied
yes, Amazon Lex sets the confirmationStatus to Confirmed, and sets the Time field in
currentIntent.slots to 4 p.m.

{
"currentIntent": {
"slots": {
"AppointmentType": "root canal",
"Date": "2017-02-15",
"Time": "16:00"
},
"name": "MakeAppointment",
"confirmationStatus": "Confirmed"
},

147
Amazon Lex Developer Guide
Example Bot: BookTrip

"bot": {
"alias": null,
"version": "$LATEST",
"name": "ScheduleAppointment"
},
"userId": "u3fpr9gghj02zts7y5tpq5mm4din2xqy",
"invocationSource": "FulfillmentCodeHook",
"outputDialogMode": "Text",
"messageVersion": "1.0",
"sessionAttributes": {
}
}

Because the confirmationStatus is confirmed, the Lambda function processes the intent (books
a dental appointment) and returns the following response to Amazon Lex:

{
"dialogAction": {
"message": {
"content": "Okay, I have booked your appointment. We will see you at 4:00
p.m. on 2017-02-15",
"contentType": "PlainText"
},
"type": "Close",
"fulfillmentState": "Fulfilled"
},
"sessionAttributes": {
"formattedTime": "4:00 p.m.",
"bookingMap": "{\"2017-02-15\": [\"10:00\"]}"
}
}

Note the following:

• The Lambda function has updated the sessionAttributes.


• dialogAction.type is set to Close, which directs Amazon Lex to not expect a user response.
• dialogAction.fulfillmentState is set to Fulfilled, indicating that the intent is
successfully fulfilled.

The client displays the message: Okay, I have booked your appointment. We will see you at 4:00
p.m. on 2017-02-15.

Example Bot: BookTrip


This example illustrates creating a bot that is configured to support multiple intents. The example
also illustrates how you can use session attributes for cross-intent information sharing. After creating
the bot, you use a test client in the Amazon Lex console to test the bot (BookTrip). The client uses the
PostText (p. 335) runtime API operation to send requests to Amazon Lex for each user input.

The BookTrip bot in this example is configured with two intents (BookHotel and BookCar). For example,
suppose a user first books a hotel. During the interaction, the user provides information such as check-in
dates, location, and number of nights. After the intent is fulfilled, the client can persist this information
using session attributes. For more information about session attributes, see PostText (p. 335).

Now suppose that the user continues to book a car. Using information that the user provided in the
previous BookHotel intent (that is, destination city, and check-in and check-out dates), the code hook
(Lambda function) you configured to initialize and validate the BookCar intent, initializes slot data for

148
Amazon Lex Developer Guide
Step 1: Blueprint Review

the BookCar intent (that is, destination, pick-up city, pick-up date, and return date). This illustrates how
cross-intent information sharing enables you to build bots that can engage in dynamic conversation with
the user.

In this example, we use the following session attributes. Only the client and the Lambda function can
set and update session attributes. Amazon Lex only passes these between the client and the Lambda
function. Amazon Lex doesn't maintain or modify any session attributes.

• currentReservation – Contains slot data for an in-progress reservation and other relevant
information. For example, the following is a sample request from the client to Amazon Lex. It shows
the currentReservation session attribute in the request body.

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"Chicago",
"sessionAttributes":{
"currentReservation":"{\"ReservationType\":\"Hotel\",
\"Location\":\"Moscow\",
\"RoomType\":null,
\"CheckInDate\":null,
\"Nights\":null}"
}
}

 
• lastConfirmedReservation – Contains similar information for a previous intent, if any. For
example, if the user booked a hotel and then is in process of booking a car, this session attribute stores
slot data for the previous BookHotel intent.

 
• confirmationContext – The Lambda function sets this to AutoPopulate when it prepopulates
some of the slot data based on slot data from the previous reservation (if there is one). This enables
cross-intent information sharing. For example, if the user previously booked a hotel and now wants to
book a car, Amazon Lex can prompt the user to confirm (or deny) that the car is being booked for the
same city and dates as their hotel reservation

In this exercise you use blueprints to create an Amazon Lex bot and a Lambda function. For more
information about blueprints, see Amazon Lex and AWS Lambda Blueprints (p. 108).

Next Step

Step 1: Review the Blueprints Used in this Exercise (p. 149)

Step 1: Review the Blueprints Used in this Exercise


Topics
• Overview of the Bot Blueprint (BookTrip) (p. 149)
• Overview of the Lambda Function Blueprint (lex-book-trip-python) (p. 151)

Overview of the Bot Blueprint (BookTrip)


The blueprint (BookTrip) you use to create a bot provides the following preconfiguration:

149
Amazon Lex Developer Guide
Step 1: Blueprint Review

• Slot types – Two custom slot types:


• RoomTypes with enumeration values: king, queen, and deluxe, for use in the BookHotel intent.
• CarTypes with enumeration values: economy, standard, midsize, full size, luxury, and
minivan, for use in the BookCar intent.

 
• Intent 1 (BookHotel) – It is preconfigured as follows:
• Preconfigured slots
• RoomType, of the RoomTypes custom slot type
• Location, of the AMAZON.US_CITY built-in slot type
• CheckInDate, of the AMAZON.DATE built-in slot type
• Nights, of the AMAZON.NUMBER built-in slot type
• Preconfigured utterances
• "Book a hotel"
• "I want to make hotel reservations"
• "Book a {Nights} stay in {Location}"

If the user utters any of these, Amazon Lex determines that BookHotel is the intent and then
prompts the user for slot data.
• Preconfigured prompts
• Prompt for the Location slot – "What city will you be staying in?"
• Prompt for the CheckInDate slot – "What day do you want to check in?"
• Prompt for the Nights slot – "How many nights will you be staying?"
• Prompt for the RoomType slot – "What type of room would you like, queen, king, or deluxe?"
• Confirmation statement – "Okay, I have you down for a {Nights} night stay in {Location} starting
{CheckInDate}. Shall I book the reservation?"
• Denial – "Okay, I have cancelled your reservation in progress."

 
• Intent 2 (BookCar) – It is preconfigured as follows:
• Preconfigured slots
• PickUpCity, of the AMAZON.US_CITY built-in type
• PickUpDate4, of the AMAZON.DATE built-in type
• ReturnDate, of the AMAZON.DATE built-in type
• DriverAge, of the AMAZON.NUMBER built-in type
• CarType, of the CarTypes custom type
• Preconfigured utterances
• "Book a car"
• "Reserve a car"
• "Make a car reservation"

If the user utters any of these, Amazon Lex determines BookCar is the intent and then prompts the
user for slot data.
• Preconfigured prompts
• Prompt for the PickUpCity slot – "In what city do you need to rent a car?"
• Prompt for the PickUpDate slot – "What day do you want to start your rental?""
150
• Prompt for the ReturnDate slot – "What day do you want to return this car?"
• Prompt for the DriverAge slot – "How old is the driver for this rental?"
Amazon Lex Developer Guide
Step 2: Create an Amazon Lex Bot

• Prompt for the CarType slot – "What type of car would you like to rent? Our most popular
options are economy, midsize, and luxury"
• Confirmation statement – "Okay, I have you down for a {CarType} rental in {PickUpCity} from
{PickUpDate} to {ReturnDate}. Should I book the reservation?"
• Denial – "Okay, I have cancelled your reservation in progress."

Overview of the Lambda Function Blueprint (lex-book-trip-


python)
In addition to the bot blueprint, AWS Lambda provides a blueprint (lex-book-trip-python) that you
can use as a code hook with the bot blueprint. For a list of bot blueprints and corresponding Lambda
function blueprints, see Amazon Lex and AWS Lambda Blueprints (p. 108).

When you create a bot using the BookTrip blueprint, you update configuration of both the intents
(BookCar and BookHotel) by adding this Lambda function as a code hook for both initialization/
validation of user data input and fulfillment of the intents.

This Lambda function code provided showcases dynamic conversation using previously known
information (persisted in session attributes) about a user to initialize slot values for an intent. For more
information, see Managing Conversation Context (p. 19).

Next Step

Step 2: Create an Amazon Lex Bot (p. 151)

Step 2: Create an Amazon Lex Bot


In this section, you create an Amazon Lex bot (BookTrip).

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. On the Bots page, choose Create.
3. On the Create your Lex bot page,

• Choose BookTrip blueprint.


• Leave the default bot name (BookTrip).
4. Choose Create. The console sends a series of requests to Amazon Lex to create the bot. Note the
following:
5. The console shows the BookTrip bot. On the Editor tab, review the details of the preconfigured
intents (BookCar and BookHotel).
6. Test the bot in the test window. Use the following to engage in a test conversation with your bot:

151
Amazon Lex Developer Guide
Step 2: Create an Amazon Lex Bot

From the initial user input ("Book a hotel"), Amazon Lex infers the intent (BookHotel). The bot then
uses the prompts preconfigured in this intent to elicit slot data from the user. After user provide all
of the slot data, Amazon Lex returns a response back to the client with a message that includes all
the user input as a message. The client displays the message in the response as shown.

CheckInDate:2016-12-18 Location:Chicago Nights:4 RoomType:queen

Now you continue the conversation and try to book a car.

152
Amazon Lex Developer Guide
Step 2: Create an Amazon Lex Bot

Note that,

• There is no user data validation at this time. For example, you can provide any city to book a hotel.
• You are providing some of the same information again (destination, pick-up city, pick-up date,
and return date) to book a car. In a dynamic conversation, your bot should initialize some of this
information based on prior input user provided for booking hotel.

In this next section, you create a Lambda function to do some of the user data validation, and
initialization using cross-intent information sharing via session attributes. Then you update the
intent configuration by adding the Lambda function as code hook to perform initialization/
validation of user input and fulfill intent.

Next Step

Step 3: Create a Lambda function (p. 154)

153
Amazon Lex Developer Guide
Step 3: Create a Lambda function

Step 3: Create a Lambda function


In this section you create a Lambda function using a blueprint (lex-book-trip-python) provided in the
Amazon Lex console. You also test the Lambda function by invoking it using sample event data provided
by the console.

This Lambda function is written in Node.js.

1. Sign in to the AWS Management Console and open the AWS Lambda console at https://
console.aws.amazon.com/lambda/.
2. Choose Create a Lambda function.
3. On Select blueprint, type lex to find the blueprint, choose the lex-book-trip-python blueprint.
4. Configure the Lambda function as follows and then choose Create Function.

• Type a Lambda function name (BookTripCodeHook).


• For the role, choose Create a new role from template(s) and then type a role name.
• Leave the other default values.
5. Test the Lambda function. You invoke the Lambda function twice, using sample data for both
booking a car and booking a hotel.

a. Choose Actions, Configure test event.


b. Choose Lex-Book Hotel (preview) from the Sample event template list.

This sample event matches the Amazon Lex request/response model. For more information, see
Using Lambda Functions (p. 101).
c. Choose Save and test.
d. Verify that the Lambda function successfully executed. The response in this case matches the
Amazon Lex response model.
e. Repeat the step. This time you choose the Lex-Book Car (preview) from the Sample event
template list. The Lambda function processes the car reservation.

Next Step

Step 4: Add the Lambda Function as a Code Hook (p. 154)

Step 4: Add the Lambda Function as a Code Hook


In this section, you update the configurations of both the BookCar and BookHotel intents by adding the
Lambda function as a code hook for initialization/validation and fulfillment activities. Make sure you
choose the $LATEST version of the intents because you can only update the $LATEST version of your
Amazon Lex resources.

1. In the Amazon Lex console, choose the BookTrip bot.


2. On the Editor tab, choose the BookHotel intent. Update the intent configuration as follows:

a. Make sure the intent version (next to the intent name) is $LATEST.
b. Add the Lambda function as an initialization and validation code hook as follows:

• In Options, choose Initialization and validation code hook.


• Choose your Lambda function from the list.
c. Add the Lambda function as a fulfillment code hook as follows:

• In Fulfillment, choose AWS Lambda function.

154
Amazon Lex Developer Guide
Step 4: Add the Lambda Function as a Code Hook

• Choose your Lambda function from the list.


• Choose Goodbye message and type a message.
d. Choose Save.
3. On the Editor tab, choose the BookCar intent. Follow the preceding step to add your Lambda
function as validation and fulfillment code hook.
4. Choose Build. The console sends a series of requests to Amazon Lex to save the configurations.
5. Test the bot. Now that you a have a Lambda function performing the initialization, user data
validation and fulfillment, you can see the difference in the user interaction.

For more information about the data flow from the client (console) to Amazon Lex, and from
Amazon Lex to the Lambda function, see Data Flow: Book Hotel Intent (p. 157).
6. Continue the conversation and book a car as shown following:

155
Amazon Lex Developer Guide
Details of the Information Flow

When you choose to book a car, the client (console) sends a request to Amazon Lex that includes the
session attributes (from the previous conversation, BookHotel). Amazon Lex passes this information
to the Lambda function, which then initializes (that is, it prepopulates) some of the BookCar slot
data (that is, PickUpDate, ReturnDate, and PickUpCity).
Note
This illustrates how session attributes can be used to maintain context across intents. The
console client provides the Clear link in the test window that a user can use to clear any
prior session attributes.

For more information about the data flow from the client (console) to Amazon Lex, and from
Amazon Lex to the Lambda function, see Data Flow: Book Car Intent (p. 165).

Details of the Information Flow


In this exercise, you engaged in a conversation with the Amazon Lex BookTrip bot using the test window
client provided in the Amazon Lex console. This section explains the following:

156
Amazon Lex Developer Guide
Details of the Information Flow

• The data flow between the client and Amazon Lex.

The section assumes that the client sends requests to Amazon Lex using the PostText runtime API
and shows request and response details accordingly. For more information about the PostText
runtime API, see PostText (p. 335).
Note
For an example of the information flow between the client and Amazon Lex in which the
client uses the PostContent API, see Step 2a (Optional): Review the Details of the Spoken
Information Flow (Console) (p. 37).

 
• The data flow between Amazon Lex and the Lambda function. For more information, see Lambda
Function Input Event and Response Format (p. 101).

Topics
• Data Flow: Book Hotel Intent (p. 157)
• Data Flow: Book Car Intent (p. 165)

Data Flow: Book Hotel Intent


This section explains what happens after each user input.

1. User: "book a hotel"

a. The client (console) sends the following PostText (p. 335) request to Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"book a hotel",
"sessionAttributes":{}
}

Both the request URI and the body provides information to Amazon Lex:

• Request URI – Provides bot name (BookTrip), bot alias ($LATEST) and the user name. The
trailing text indicates that it is a PostText API request (and not PostContent).
• Request body – Includes the user input (inputText) and empty sessionAttributes.
Initially, this is an empty object and the Lambda function first sets the session attributes.
b. From the inputText, Amazon Lex detects the intent (BookHotel). This intent is configured with
a Lambda function as a code hook for user data initialization/validation. Therefore, Amazon Lex
invokes that Lambda function by passing the following information as the event parameter (see
Input Event Format (p. 101)):

{
"messageVersion":"1.0",
"invocationSource":"DialogCodeHook",
"userId":"wch89kjqcpkds8seny7dly5x3otq68j3",
"sessionAttributes":{
},
"bot":{
"name":"BookTrip",

157
Amazon Lex Developer Guide
Details of the Information Flow

"alias":null,
"version":"$LATEST"
},
"outputDialogMode":"Text",
"currentIntent":{
"name":"BookHotel",
"slots":{
"RoomType":null,
"CheckInDate":null,
"Nights":null,
"Location":null
},
"confirmationStatus":"None"
}
}

In addition to the information sent by the client, Amazon Lex also includes the following
additional data:

• messageVersion – Currently Amazon Lex supports only the 1.0 version.


• invocationSource – Indicates the purpose of Lambda function invocation. In this case, it
is to perform user data initialization and validation (at this time Amazon Lex knows that the
user has not provided all the slot data to fulfill the intent).
• currentIntent – All of the slot values are set to null.
c. At this time, all the slot values are null. There is nothing for the Lambda function to validate.
The Lambda function returns the following response to Amazon Lex. For information about
response format, see Response Format (p. 104).

{
"sessionAttributes":{
"currentReservation":"{\"ReservationType\":\"Hotel\",\"Location\":null,
\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}"
},
"dialogAction":{
"type":"Delegate",
"slots":{
"RoomType":null,
"CheckInDate":null,
"Nights":null,
"Location":null
}
}
}

Note

• currentReservation – The Lambda function includes this session attribute. Its


value is a copy of the current slot information and the reservation type.

Only the Lambda function and the client can update these session attributes.
Amazon Lex simply passes these values.
• dialogAction.type – By setting this value to Delegate, the Lambda function
delegates the responsibility for the next course of action to Amazon Lex.

If the Lambda function detected anything in the user data validation, it instructs
Amazon Lex what to do next.
d. As per the dialogAction.type, Amazon Lex decides the next course of action—elicit data
from the user for the Location slot. It selects one of the prompt messages ("What city will you

158
Amazon Lex Developer Guide
Details of the Information Flow

be staying in?") for this slot, according to the intent configuration, and then sends the following
response to the user:

The session attributes are passed to the client.

The client reads the response and then displays the message: "What city will you be staying in?"
2. User: "Moscow"

a. The client sends the following PostText request to Amazon Lex (line breaks added for
readability):

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"Moscow",
"sessionAttributes":{
"currentReservation":"{\"ReservationType\":\"Hotel\",
\"Location\":null,
\"RoomType\":null,
\"CheckInDate\":null,
\"Nights\":null}"
}
}

In addition to the inputText, the client includes the same currentReservation session
attributes it received.
b. Amazon Lex first interprets the inputText in the context of the current intent (the service
remembers that it had asked the specific user for information about Location slot). It updates
the slot value for the current intent and invokes the Lambda function using the following event:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "wch89kjqcpkds8seny7dly5x3otq68j3",
"sessionAttributes": {
"currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":null,
\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}"
},
"bot": {
"name": "BookTrip",

159
Amazon Lex Developer Guide
Details of the Information Flow

"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "BookHotel",
"slots": {
"RoomType": null,
"CheckInDate": null,
"Nights": null,
"Location": "Moscow"
},
"confirmationStatus": "None"
}
}

Note

• invocationSource continues to be DialogCodeHook. In this step, we are just


validating user data.
• Amazon Lex is just passing the session attribute to the Lambda function.
• For currentIntent.slots, Amazon Lex has updated the Location slot to
Moscow.
c. The Lambda function performs the user data validation and determines that Moscow is an
invalid location.
Note
The Lambda function in this exercise has a simple list of valid cities and Moscow is not
on the list. In a production application, you might use a back-end database to get this
information.

It resets the slot value back to null and directs Amazon Lex to prompt the user again for another
value by sending the following response:

{
"sessionAttributes": {
"currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":\"Moscow
\",\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}"
},
"dialogAction": {
"type": "ElicitSlot",
"intentName": "BookHotel",
"slots": {
"RoomType": null,
"CheckInDate": null,
"Nights": null,
"Location": null
},
"slotToElicit": "Location",
"message": {
"contentType": "PlainText",
"content": "We currently do not support Moscow as a valid destination.
Can you try a different city?"
}
}
}

Note

• currentIntent.slots.Location is reset to null.

160
Amazon Lex Developer Guide
Details of the Information Flow

• dialogAction.type is set to ElicitSlot, which directs Amazon Lex to prompt


the user again by providing the following:
• dialogAction.slotToElicit – slot for which to elicit data from the user.
• dialogAction.message – a message to convey to the user.
d. Amazon Lex notices the dialogAction.type and passes the information to the client in the
following response:

The client simply displays the message: "We currently do not support Moscow as a valid
destination. Can you try a different city?"
3. User: "Chicago"

a. The client sends the following PostText request to Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"Chicago",
"sessionAttributes":{
"currentReservation":"{\"ReservationType\":\"Hotel\",
\"Location\":\"Moscow\",
\"RoomType\":null,
\"CheckInDate\":null,
\"Nights\":null}"
}
}

b. Amazon Lex knows the context, that it was eliciting data for the Location slot. In this context,
it knows the inputText value is for the Location slot. It then invokes the Lambda function by
sending the following event:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "wch89kjqcpkds8seny7dly5x3otq68j3",
"sessionAttributes": {
"currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":Moscow,
\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}"
},
"bot": {
"name": "BookTrip",

161
Amazon Lex Developer Guide
Details of the Information Flow

"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "BookHotel",
"slots": {
"RoomType": null,
"CheckInDate": null,
"Nights": null,
"Location": "Chicago"
},
"confirmationStatus": "None"
}
}

Amazon Lex updated the currentIntent.slots by setting the Location slot to Chicago.
c. According to the invocationSource value of DialogCodeHook, the Lambda function
performs user data validation. It recognizes Chicago as a valid slot value, updates the session
attribute accordingly, and then returns the following response to Amazon Lex.

{
"sessionAttributes": {
"currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":
\"Chicago\",\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}"
},
"dialogAction": {
"type": "Delegate",
"slots": {
"RoomType": null,
"CheckInDate": null,
"Nights": null,
"Location": "Chicago"
}
}
}

Note

• currentReservation – The Lambda function updates this session attribute by


setting the Location to Chicago.
• dialogAction.type – Is set to Delegate. User data was valid, and the Lambda
function directs Amazon Lex to choose the next course of action.

 
d. According to dialogAction.type, Amazon Lex chooses the next course of action. Amazon
Lex knows that it needs more slot data and picks the next unfilled slot (CheckInDate) with the
highest priority according to the intent configuration. It selects one of the prompt messages
("What day do you want to check in?") for this slot according to the intent configuration and
then sends the following response back to the client:

162
Amazon Lex Developer Guide
Details of the Information Flow

The client displays the message: "What day do you want to check in?"
4. The user interaction continues—the user provides data, the Lambda function validates data, and
then delegates the next course of action to Amazon Lex. Eventually the user provides all of the slot
data, the Lambda function validates all of the user input, and then Amazon Lex recognizes it has all
the slot data.
Note
In this exercise, after the user provides all of the slot data, the Lambda function
computes the price of the hotel reservation and returns it as another session attribute
(currentReservationPrice).

At this point, the intent is ready to be fulfilled, but the BookHotel intent is configured with a
confirmation prompt requiring user confirmation before Amazon Lex can fulfill the intent. Therefore,
Amazon Lex sends the following message to the client requesting confirmation before booking the
hotel:

The client display the message: "Okay, I have you down for a 5 night in Chicago starting 2016-12-18.
Shall I book the reservation?"
5. User: "yes"

a. The client sends the following PostText request to Amazon Lex:

163
Amazon Lex Developer Guide
Details of the Information Flow

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"Yes",
"sessionAttributes":{
"currentReservation":"{\"ReservationType\":\"Hotel\",
\"Location\":\"Chicago\",
\"RoomType\":\"queen\",
\"CheckInDate\":\"2016-12-18\",
\"Nights\":\"5\"}",
"currentReservationPrice":"1195"
}
}

b. Amazon Lex interprets the inputText in the context of confirming the current intent. Amazon
Lex understands that the user wants to proceed with the reservation. This time Amazon Lex
invokes the Lambda function to fulfill the intent by sending the following event. By setting the
invocationSource to FulfillmentCodeHook in the event, it sends to the Lambda function.
Amazon Lex also sets the confirmationStatus to Confirmed.

{
"messageVersion": "1.0",
"invocationSource": "FulfillmentCodeHook",
"userId": "wch89kjqcpkds8seny7dly5x3otq68j3",
"sessionAttributes": {
"currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":
\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\":
\"4\"}",
"currentReservationPrice": "956"
},
"bot": {
"name": "BookTrip",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "BookHotel",
"slots": {
"RoomType": "queen",
"CheckInDate": "2016-12-18",
"Nights": "4",
"Location": "Chicago"
},
"confirmationStatus": "Confirmed"
}
}

Note

• invocationSource – This time, Amazon Lex set this value to


FulfillmentCodeHook, directing the Lambda function to fulfill the intent.
• confirmationStatus – Is set to Confirmed.
c. This time, the Lambda function fulfills the BookHotel intent, Amazon Lex completes the
reservation, and then it returns the following response:

{
"sessionAttributes": {

164
Amazon Lex Developer Guide
Details of the Information Flow

"lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location
\":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\":
\"4\"}"
},
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": "Thanks, I have placed your reservation. Please let me
know if you would like to book a car rental, or another hotel."
}
}
}

Note

• lastConfirmedReservation – Is a new session attribute that


the Lambda function added (instead of the currentReservation,
currentReservationPrice).
• dialogAction.type – The Lambda function sets this value to Close, indicating
that Amazon Lex to not expect a user response.
• dialogAction.fulfillmentState – Is set to Fulfilled and includes an
appropriate message to convey to the user.
d. Amazon Lex reviews the fulfillmentState and sends the following response to the client:

Note

• dialogState – Amazon Lex sets this value to Fulfilled.


• message – Is the same message that the Lambda function provided.

The client displays the message.

Data Flow: Book Car Intent


The BookTrip bot in this exercise supports two intents (BookHotel and BookCar). After booking a
hotel, the user can continue the conversation to book a car. As long as the session hasn't timed out,
in each subsequent request the client continues to send the session attributes (in this example, the
lastConfirmedReservation). The Lambda function can use this information to initialize slot data for
the BookCar intent. This shows how you can use session attributes in cross-intent data sharing.

165
Amazon Lex Developer Guide
Details of the Information Flow

Specifically, when the user chooses the BookCar intent, the Lambda function uses relevant information
in the session attribute to prepopulate slots (PickUpDate, ReturnDate, and PickUpCity) for the BookCar
intent.
Note
The Amazon Lex console provides the Clear link that you can use to clear any prior session
attributes.

Follow the steps in this procedure to continue the conversation.

1. User: "also book a car"

a. The client sends the following PostText request to Amazon Lex.

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"also book a car",
"sessionAttributes":{
"lastConfirmedReservation":""{\"ReservationType\":\"Hotel\",
\"Location\":\"Chicago\",
\"RoomType\":\"queen\",
\"CheckInDate\":\"2016-12-18\",
\"Nights\":\"5\"}"
}
}

The client includes the lastConfirmedReservation session attribute.


b. Amazon Lex detects the intent (BookCar) from the inputText. This intent is also configured
to invoke the Lambda function to perform the initialization and validation of the user data.
Amazon Lex invokes the Lambda function with the following event:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "wch89kjqcpkds8seny7dly5x3otq68j3",
"sessionAttributes": {
"lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location
\":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\":
\"4\"}"
},
"bot": {
"name": "BookTrip",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "BookCar",
"slots": {
"PickUpDate": null,
"ReturnDate": null,
"DriverAge": null,
"CarType": null,
"PickUpCity": null
},
"confirmationStatus": "None"
}
}

166
Amazon Lex Developer Guide
Details of the Information Flow

Note

• messageVersion – Currently Amazon Lex supports the 1.0 version only.


• invocationSource – Indicates the purpose of invocation is to perform initialization
and user data validation.
• currentIntent – It includes the intent name and the slots. At this time, all slot
values are null.
c. The Lambda function notices all null slot values with nothing to validate. However, it uses
session attributes to initialize some of the slot values (PickUpDate, ReturnDate, and
PickUpCity), and then returns the following response:

{
"sessionAttributes": {
"lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location
\":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\":
\"4\"}",
"currentReservation": "{\"ReservationType\":\"Car\",\"PickUpCity\":null,
\"PickUpDate\":null,\"ReturnDate\":null,\"CarType\":null}",
"confirmationContext": "AutoPopulate"
},
"dialogAction": {
"type": "ConfirmIntent",
"intentName": "BookCar",
"slots": {
"PickUpCity": "Chicago",
"PickUpDate": "2016-12-18",
"ReturnDate": "2016-12-22",
"CarType": null,
"DriverAge": null
},
"message": {
"contentType": "PlainText",
"content": "Is this car rental for your 4 night stay in Chicago on
2016-12-18?"
}
}
}

Note

• In addition to the lastConfirmedReservation, the Lambda function includes


more session attributes (currentReservation and confirmationContext).
• dialogAction.type is set to ConfirmIntent, which informs Amazon Lex
that a yes, no reply is expected from the user (the confirmationContext set to
AutoPopulate, the Lambda function knows that the yes/no user reply is to obtain
user confirmation of the initialization the Lambda function performed (auto
populated slot data).

The Lambda function also includes in the response an informative message in the
dialogAction.message for Amazon Lex to return to the client.
Note
The term ConfirmIntent (value of the dialogAction.type) is not
related to any bot intent. In the example, Lambda function uses this term to
direct Amazon Lex to get a yes/no reply from the user.
d. According to the dialogAction.type, Amazon Lex returns the following response to the
client:

167
Amazon Lex Developer Guide
Details of the Information Flow

The client displays the message: "Is this car rental for your 5 night stay in Chicago on
2016-12-18?"
2. User: "yes"

a. The client sends the following PostText request to Amazon Lex.

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text
"Content-Type":"application/json"
"Content-Encoding":"amz-1.0"

{
"inputText":"yes",
"sessionAttributes":{
"confirmationContext":"AutoPopulate",
"currentReservation":"{\"ReservationType\":\"Car\",
\"PickUpCity\":null,
\"PickUpDate\":null,
\"ReturnDate\":null,
\"CarType\":null}",
"lastConfirmedReservation":"{\"ReservationType\":\"Hotel\",
\"Location\":\"Chicago\",
\"RoomType\":\"queen\",
\"CheckInDate\":\"2016-12-18\",
\"Nights\":\"5\"}"
}
}

b. Amazon Lex reads the inputText and it knows the context (asked the user to confirm the auto
population). Amazon Lex invokes the Lambda function by sending the following event:

{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "wch89kjqcpkds8seny7dly5x3otq68j3",
"sessionAttributes": {
"confirmationContext": "AutoPopulate",
"currentReservation": "{\"ReservationType\":\"Car\",\"PickUpCity\":null,
\"PickUpDate\":null,\"ReturnDate\":null,\"CarType\":null}",

168
Amazon Lex Developer Guide
Details of the Information Flow

"lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location
\":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\":
\"4\"}"
},
"bot": {
"name": "BookTrip",
"alias": null,
"version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
"name": "BookCar",
"slots": {
"PickUpDate": "2016-12-18",
"ReturnDate": "2016-12-22",
"DriverAge": null,
"CarType": null,
"PickUpCity": "Chicago"
},
"confirmationStatus": "Confirmed"
}
}

Because the user replied Yes, Amazon Lex sets the confirmationStatus to Confirmed.
c. From the confirmationStatus, the Lambda function knows that the prepopulated values are
correct. The Lambda function does the following:

• Updates the currentReservation session attribute to slot value it had prepopulated.


• Sets the dialogAction.type to ElicitSlot
• Sets the slotToElicit value to DriverAge.

The following response is sent:

{
"sessionAttributes": {
"currentReservation": "{\"ReservationType\":\"Car\",\"PickUpCity\":
\"Chicago\",\"PickUpDate\":\"2016-12-18\",\"ReturnDate\":\"2016-12-22\",\"CarType
\":null}",
"lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location
\":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\":
\"4\"}"
},
"dialogAction": {
"type": "ElicitSlot",
"intentName": "BookCar",
"slots": {
"PickUpDate": "2016-12-18",
"ReturnDate": "2016-12-22",
"DriverAge": null,
"CarType": null,
"PickUpCity": "Chicago"
},
"slotToElicit": "DriverAge",
"message": {
"contentType": "PlainText",
"content": "How old is the driver of this car rental?"
}
}
}

d. Amazon Lex returns following response:

169
Amazon Lex Developer Guide
Example: Using a Response Card

The client displays the message "How old is the driver of this car rental?" and the conversation
continues.

Example: Using a Response Card


In this exercise, you extend Getting Started Exercise 1 by adding a response card. You create a bot
that supports the OrderFlowers intent, and then update the intent by adding a response card for the
FlowerType slot. In addition to the following prompt for the FlowerType slot, the user can choose the
type of flowers from the response card:

What type of flowers would you like to order?

The following is the response card:

170
Amazon Lex Developer Guide
Example: Using a Response Card

The bot user can either type the text or choose from the list of flower types. This response card is
configured with an image, which appears in the client as shown. For more information about response
cards, see Response Cards (p. 15).

To create and test a bot with a response card:

1. Follow Getting Started Exercise 1 to create and test an OrderFlowers bot. You must complete steps
1, 2, and 3. You don't need to add a Lambda function to test the response card. For instructions, see
Exercise 1: Create an Amazon Lex Bot Using a Blueprint (Console) (p. 33).
2. Update the bot by adding the response card, and then publish a version. When you publish a version,
specify an alias (BETA) to point to it.

a. In the Amazon Lex console, choose your bot.


b. Choose the OrderFlowers intent.
c. Choose the settings gear icon next to the "What type of flowers" Prompt to configure a
response card for the FlowerType.

171
Amazon Lex Developer Guide
Example: Using a Response Card

d. Give the card a title and configure three buttons as shown in the following screen shot. You
can optionally add an image to the response card, provided you have an image URL. If you are
deploying your bot using Twilio SMS, you must provide an image URL.

172
Amazon Lex Developer Guide
Example: Updating Utterances

e. Choose Save to save the response card.


f. Choose Save intent to save the intent configuration.
g. To build the bot, choose Build.
h. To publish a bot version, choose Publish. Specify BETA as an alias that points to the bot version.
For information about versioning, see Versioning and Aliases (p. 97).
3. Deploy the bot on a messaging platform:

• Deploy the bot on the Facebook Messenger platform and test the integration. For instructions, see
Integrating an Amazon Lex Bot with Facebook Messenger (p. 111). When you order flowers, the
message window shows the response card so you can choose a flower type.
• Deploy the bot on the Slack platform and test the integration. For instructions, see Integrating
an Amazon Lex Bot with Slack (p. 116). When you order flowers, the message window shows the
response card so you can choose a flower type.
• Deploy the bot on the Twilio SMS platform. For instructions, see Integrating an Amazon Lex Bot
with Twilio Programmable SMS (p. 120). When you order flowers, the message from Twilio shows
the image from the response card. Twilio SMS does not support buttons in the response.

Example: Updating Utterances


In this exercise, you add additional utterances to those you created in Getting Started Exercise 1. You use
the Monitoring tab in the Amazon Lex console to view utterances that your bot did not recognize. To
improve the experience for your users, you add those utterances to the bot.
Note
Utterance statistics are generated once a day. You can see the utterance that was not
recognized, how many times it was heard, and the last date and time that the utterance was
heard. It can take up to 24 hours for missed utterances to appear in the console.

To view and add missed utterances to a bot:

1. Follow the first step of Getting Started Exercise 1 to create and test an OrderFlowers bot. For
instructions, see Exercise 1: Create an Amazon Lex Bot Using a Blueprint (Console) (p. 33).
2. Test the bot by typing the following utterances in the Test Bot window. Type each utterance several
times. The example bot doesn't recognize the following utterances:

• Order flowers
• Get me flowers
• Please order flowers
• Get me some flowers
3. Wait for Amazon Lex to gather usage data about the missed utterances. Utterance data is generated
once per day, generally overnight.
4. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
5. Choose the OrderFlowers bot.
6. Choose the Monitoring tab, and then choose Utterances from the left menu and then choose the
Missed button. The pane shows a maximum of 100 missed utterances.

173
Amazon Lex Developer Guide
Example: Integrating with a Web site

7. To choose the missed utterances that you want to add to the bot, select the check box next to them.
To add the utterance to the $LATEST version of the intent, choose the down arrow next to the Add
utterance to intent dropdown, and then choose the intent.
8. To rebuild your bot, choose Build and then Build again to re-build your bot.
9. To verify that your bot recognizes the new utterances, use the Test Bot pane.

Example: Integrating with a Web site


In this example you integrate a bot with a Web site using text and voice. You use JavaScript and AWS
services to build an interactive experience for visitors to your Web site. You can choose from these
examples documented on the AWS AI Blog:

• Deploy a Web UI for Your Chatbot—Demonstrates a full-featured Web UI that provides a Web client
for Amazon Lex chatbots. You can use this to learn about Web clients, or as a building block for your
own application.

 
• "Greetings, visitor!"—Engage Your Web Users with Amazon Lex—Demonstrates using Amazon Lex, the
AWS SDK for JavaScript in the Browser, and Amazon Cognito to create a conversational experience on
your Web site.

 
• Capturing Voice Input in a Browser and Sending it to Amazon Lex—Demonstrates embedding a voice-
based chatbot in a Web site using the SDK for JavaScript in the Browser. The application records audio,
sends the audio to Amazon Lex, and then plays the response.

174
Amazon Lex Developer Guide
Monitoring Amazon Lex with CloudWatch

Monitoring Amazon Lex


Monitoring is important for maintaining the reliability, availability, and performance of your Amazon
Lex chatbots. This topic describes how to use Amazon CloudWatch Logs and AWS CloudTrail to monitor
Amazon Lex and describes the Amazon Lex runtime and channel association metrics.

Topics
• Monitoring Amazon Lex with Amazon CloudWatch (p. 175)
• Monitoring Amazon Lex API Calls with AWS CloudTrail Logs (p. 180)

Monitoring Amazon Lex with Amazon CloudWatch


To track the health of your Amazon Lex bots, use Amazon CloudWatch. With CloudWatch, you can get
metrics for individual Amazon Lex operations or for global Amazon Lex operations for your account. You
can also set up CloudWatch alarms to be notified when one or more metrics exceeds a threshold that
you define. For example, you can monitor the number of requests made to a bot over a particular time
period, view the latency of successful requests, or raise an alarm when errors exceed a threshold.

CloudWatch Metrics for Amazon Lex


To get metrics for your Amazon Lex operations , you must specify the following information:

• The metric dimension. A dimension is a set of name-value pairs that you use to identify a metric.
Amazon Lex has three dimensions:
• BotAlias, BotName, Operation
• BotAlias, BotName, InputMode, Operation
• BotName, BotVersion, InputMode, Operation
• The metric name, such as MissedUtteranceCount or RuntimeRequestCount.

You can get metrics for Amazon Lex with the AWS Management Console, the AWS CLI, or the
CloudWatch API. You can use the CloudWatch API through one of the Amazon AWS Software
Development Kits (SDKs) or the CloudWatch API tools. The Amazon Lex console displays graphs based on
the raw data from the CloudWatch API.

You must have the appropriate CloudWatch permissions to monitor Amazon Lex with CloudWatch
For more information, see Authentication and Access Control for Amazon CloudWatch in the Amazon
CloudWatch User Guide.

Viewing Amazon Lex Metrics


View Amazon Lex metrics using the Amazon Lex console and the CloudWatch console.

To view metrics (Amazon Lex console)

1. Sign in to the AWS Management Console and open the Amazon Lex console at https://
console.aws.amazon.com/lex/.
2. From the list of bots, choose the one whose metrics you want to see.
3. Choose Monitoring. Metrics are displayed in graphs.

175
Amazon Lex Developer Guide
Creating an Alarm

To view metrics (CloudWatch console)

1. Sign in to the AWS Management Console and open the CloudWatch console at https://
console.aws.amazon.com/cloudwatch/.
2. Choose Metrics, choose All Metrics, and then choose AWS/Lex.
3. Choose the dimension, and then choose a metric name. Choose Add to graph.
4. Choose a value for the date range. The metric count for the selected date range is displayed in the
graph.

Creating an Alarm
A CloudWatch alarm watches a single metric over a time period that you specify, and performs one or
more actions: sending a notification to an Amazon SNS topic or Auto Scaling policy. The action or actions
are based on the value of the metric relative to a given threshold over a number of time periods that you
specify. CloudWatch can also send you an Amazon Simple Notification Service (Amazon SNS) message
when the alarm changes state.

CloudWatch alarms invoke actions only when the state changes and has persisted for the period that you
specify.

To set an alarm

1. Sign in to the AWS Management Console and open the CloudWatch console at https://
console.aws.amazon.com/cloudwatch/.
2. Choose Alarms, and then choose Create Alarm.
3. Choose AWS/Lex Metrics, and then choose a metric.
4. For Time Range, choose a time range to monitor, and then choose Next.
5. Type a Name and Description.
6. For Whenever, choose >=, and type a maximum value.
7. If you want CloudWatch to send an email when the alarm state is reached, in the Actions section,
for Whenever this alarm, choose State is ALARM. For Send notification to, choose a mailing list or
choose New list and create a new mailing list.
8. Preview the alarm in the Alarm Preview section. If you are satisfied with the alarm, choose Create
Alarm.

CloudWatch Metrics for Amazon Lex Runtime


The following table describes the Amazon Lex runtime metrics.

Metric Description

The number of invalid Lambda responses in the specified period.


RuntimeInvalidLambdaResponses

Valid dimension for the PostContentoperation with the Text or


Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Valid dimension for the PostText operation:

• BotName, BotAlias, Operation

176
Amazon Lex Developer Guide
Runtime Metrics for Amazon Lex

Metric Description

RuntimeLambdaErrors The number of AWS Lambda runtime errors in the specified period.

Valid dimension for the PostContent operation with the Text or


Speech InputMode :

• BotName, BotAlias, Operation, InputMode

Valid dimension for the PostText operation:

• BotName, BotAlias, Operation

MissedUtteranceCount The number of utterances that were not recognized in the specified
period.

Valid dimensions for the PostContent operation with the Text or


Speech InputMode:

• BotName, BotVersion, Operation, InputMode


• BotName, BotAlias, Operation, InputMode

Valid dimensions for the PostText operation:

• BotName, BotVersion, Operation


• BotName, BotAlias, Operation

RuntimePollyErrors The number of invalid Amazon Polly responses in the specified period.

Valid dimension for the PostContent operation with the Text or


Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Valid dimension for the PostText operation:

• BotName, BotAlias, Operation

RuntimeRequestCount The number of runtime requests in the specified period.

Valid dimensions for the PostContent operation with the Text or


Speech InputMode:

• BotName, BotVersion, Operation, InputMode


• BotName, BotAlias, Operation, InputMode

Valid dimensions for the PostText operation:

• BotName, BotVersion, Operation


• BotName, BotAlias, Operation

Unit: Count

177
Amazon Lex Developer Guide
Runtime Metrics for Amazon Lex

Metric Description

The latency for successful requests between the time that the request
RuntimeSucessfulRequestLatency
was made and the response was passed back.

Valid dimensions for the PostContent operation with the Text or


Speech InputMode:

• BotName, BotVersion, Operation, InputMode


• BotName, BotAlias, Operation, InputMode

Valid dimensions for the PostText operation:

• BotName, BotVersion, Operation


• BotName, BotAlias, Operation

Unit: Milliseconds

RuntimeSystemErrors The number of system errors in the specified period. The response code
range for a system error is 500 to 599.

Valid dimension for the PostContent operation with the Text or


Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Valid dimension for the PostText operation:

• BotName, BotAlias, Operation

Unit: Count

RuntimeThrottledEvents The number of throttled requests. Amazon Lex throttles a request when
it receives more requests than the limit of transactions per second set
for your account. If the limit set for your account is frequently exceeded,
you can request a limit increase. To request an increase, see AWS Service
Limits.

Valid dimension for the PostContent operation with the Text or


Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Valid dimension for the PostText operation:

• BotName, BotAlias, Operation

Unit: Count

178
Amazon Lex Developer Guide
Channel Association Metrics for Amazon Lex

Metric Description

RuntimeUserErrors The number of user errors in the specified period. The response code
range for a user error is 400 to 499.

Valid dimension for the PostContent operation with Text or Speech


InputMode:

• BotName, BotAlias, Operation, InputMode

Valid dimension for the PostText operation:

• BotName, BotAlias, Operation

Unit: Count

Amazon Lex runtime metrics use the AWS/Lex namespace, and provide metrics in the following
dimensions. You can group metrics by dimenstions in the CloudWatch console:

Dimension Description

BotName, BotAlias, Groups metrics by the bot's alias, the bot's name, the operation
Operation, InputMode (PostContent), and by whether the input was text or speech.

BotName, BotVersion, Groups metrics by the bot's name, the version of the bot, the operation
Operation, InputMode (PostContent), and by whether the input was text or speech.

BotName, BotVersion, Groups metrics by the bot's name, the bots version, and by the
Operation operation, PostText.

BotName, BotAlias, Groups metrics by the bot's name, the bot's alias, and by the operation,
Operation PostText.

CloudWatch Metrics for Amazon Lex Channel


Associations
A channel association is the association between Amazon Lex and a messaging channel, such as
Facebook. The following table describes the Amazon Lex channel association metrics.

Metric Description

BotChannelAuthErrors The number of authentication errors returned by the messaging channel


in the specified time period. An authentication error indicates that the
secret token provided during channel creation is invalid or has expired.

The number of configuration errors in the specified period. A


BotChannelConfigurationErrors
configuration error indicates that one or more configuration entries for
the channel are invalid.

The number of times that messages that were sent by the messaging
BotChannelInboundThrottledEvents
channel were throttled by Amazon Lex in the specified period.

179
Amazon Lex Developer Guide
Logging Amazon Lex API Calls with AWS CloudTrail

Metric Description

The number of times that outbound events from Amazon Lex to the
BotChannelOutboundThrottledEvents
messaging channel were throttled in the specified time period.

BotChannelRequestCount The number of requests made on a channel in the specified time period.

The number of times that Amazon Lex could not post response cards in
BotChannelResponseCardErrors
the specified period.

BotChannelSystemErrors The number of internal errors that occurred in Amazon Lex for a channel
in the specified period.

Amazon Lex channel association metrics use the AWS/Lex namespace, and provide metrics for the
following dimension. You can group metrics by dimenstions in the CloudWatch console::

Dimension Description

BotAlias, Group metrics by the bot's alias, the channel name, the bot's name, and
BotChannelName, by the source of traffic.
BotName, Source

Monitoring Amazon Lex API Calls with AWS


CloudTrail Logs
Amazon Lex is integrated with AWS CloudTrail, a service that provides a record of actions taken by a
user, role, or an AWS service in Amazon Lex. CloudTrail captures a subset of API calls for Amazon Lex as
events, including calls from the Amazon Lex console and from code calls to the Amazon Lex APIs. If you
create a trail, you can enable continuous delivery of CloudTrail events to an Amazon S3 bucket, including
events for Amazon Lex. If you don't configure a trail, you can still view the most recent events in the
CloudTrail console in Event history. Using the information collected by CloudTrail, you can determine
the request that was made to Amazon Lex, the IP address from which the request was made, who made
the request, when it was made, and additional details.

To learn more about CloudTrail, including how to configure and enable it, see the AWS CloudTrail User
Guide.

Amazon Lex Information in CloudTrail


CloudTrail is enabled on your AWS account when you create the account. When supported event activity
occurs in Amazon Lex, that activity is recorded in a CloudTrail event along with other AWS service events
in Event history. You can view, search, and download recent events in your AWS account. For more
information, see Viewing Events with CloudTrail Event History.

For an ongoing record of events in your AWS account, including events for Amazon Lex, create a trail. A
trail enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create a trail
in the console, the trail applies to all regions. The trail logs events from all regions in the AWS partition
and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can configure
other AWS services to further analyze and act upon the event data collected in CloudTrail logs. For more
information, see:

• Overview for Creating a Trail

180
Amazon Lex Developer Guide
Example: Amazon Lex Log File Entries

• CloudTrail Supported Services and Integrations


• Configuring Amazon SNS Notifications for CloudTrail
• Receiving CloudTrail Log Files from Multiple Regions and Receiving CloudTrail Log Files from Multiple
Accounts

Amazon Lex supports logging the following actions as events in CloudTrail log files:

• CreateBotVersion (p. 205)


• CreateIntentVersion (p. 210)
• CreateSlotTypeVersion (p. 216)
• PutBot (p. 297)
• PutBotAlias (p. 305)
• PutIntent (p. 309)
• PutSlotType (p. 319)

Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:

• Whether the request was made with root or IAM user credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.

For more information, see the CloudTrail userIdentity Element.

For information about the Amazon Lex actions that are logged in CloudTrail logs, see Amazon Lex Model
Building Service. For example, calls to the PutBot (p. 297), GetBot (p. 238), and DeleteBot (p. 220)
operations generate entries in the CloudTrail log. The actions documented in Amazon Lex Runtime
Service, PostContent (p. 327) and PostText (p. 335), are not logged.

Example: Amazon Lex Log File Entries


A trail is a configuration that enables delivery of events as log files to an Amazon S3 bucket that you
specify. CloudTrail log files contain one or more log entries. An event represents a single request from
any source and includes information about the requested action, the date and time of the action, request
parameters, and so on. CloudTrail log files are not an ordered stack trace of the public API calls, so they
do not appear in any specific order.

The following example CloudTrail log entry shows the result of a call to the PutBot action.

{
"eventVersion": "1.05",
"userIdentity": {
"type": "AssumedRole | FederatedUser | IAMUser | Root | SAMLUser |
WebIdentityUser",
"principalId": "principal ID",
"arn": "ARN",
"accountId": "account ID",
"accessKeyId": "access key ID",
"userName": "user name"
},
"eventTime": "timestamp",
"eventSource": "lex.amazonaws.com",
"eventName": "PutBot",
"awsRegion": "region",

181
Amazon Lex Developer Guide
Example: Amazon Lex Log File Entries

"sourceIPAddress": "source IP address",


"userAgent": "user agent",
"requestParameters": {
"name": "CloudTrailBot",
"intents": [
{
"intentVersion": "11",
"intentName": "TestCloudTrail"
}
],
"voiceId": "Salli",
"childDirected": false,
"locale": "en-US",
"idleSessionTTLInSeconds": 500,
"processBehavior": "BUILD",
"description": "CloudTrail test bot",
"clarificationPrompt": {
"messages": [
{
"contentType": "PlainText",
"content": "I didn't understand you, what would you like to
do?"
}
],
"maxAttempts": 2
},
"abortStatement": {
"messages": [
{
"contentType": "PlainText",
"content": "Sorry. I'm not able to assist at this time."
}
]
}
},
"responseElements": {
"voiceId": "Salli",
"locale": "en-US",
"childDirected": false,
"abortStatement": {
"messages": [
{
"contentType": "PlainText",
"content": "Sorry. I'm not able to assist at this time."
}
]
},
"status": "BUILDING",
"createdDate": "timestamp",
"lastUpdatedDate": "timestamp",
"idleSessionTTLInSeconds": 500,
"intents": [
{
"intentVersion": "11",
"intentName": "TestCloudTrail"
}
],
"clarificationPrompt": {
"messages": [
{
"contentType": "PlainText",
"content": "I didn't understand you. What would you like to
do?"
}
],
"maxAttempts": 2

182
Amazon Lex Developer Guide
Example: Amazon Lex Log File Entries

},
"version": "$LATEST",
"description": "CloudTrail test bot",
"checksum": "checksum",
"name": "CloudTrailBot"
},
"requestID": "request ID",
"eventID": "event ID",
"eventType": "AwsApiCall",
"recipientAccountId": "account ID"
}
}

183
Amazon Lex Developer Guide
General Guidelines

Guidelines and Limits in Amazon Lex


The following sections provide guidelines and limits when using Amazon Lex.

Topics
• General Guidelines (p. 184)
• Limits (p. 186)

General Guidelines
This section describes general guidelines when using Amazon Lex.

• Signing requests – All Amazon Lex model-building and runtime API operations in the API
Reference (p. 202) use signature V4 for authenticating requests. For more information about
authenticating requests, see Signature Version 4 Signing Process in the Amazon Web Services General
Reference.

For PostContent (p. 327), Amazon Lex uses the unsigned payload option described in Signature
Calculations for the Authorization Header: Transferring Payload in a Single Chunk (AWS Signature
Version 4) in the Amazon Simple Storage Service (S3) API Reference.

When you use the unsigned payload option, don't include the hash of the payload in the canonical
request. Instead, you use the literal string "UNSIGNED-PAYLOAD" as the hash of the payload. Also
include a header with the name x-amz-content-sha256 and the value UNSIGNED-PAYLOAD in the
PostContent request.

 
• Note the following about how Amazon Lex captures slot values from user utterances:

Amazon Lex uses the enumeration values you provide in a slot type definition to train its machine
learning models. Suppose you define an intent called GetPredictionIntent with the following
sample utterance:

"Tell me the prediction for {Sign}"

Where {Sign} is a slot of custom type ZodiacSign. It has 12 enumeration values, Aries through
Pisces. From the user utterance "Tell me the prediction for ..." Amazon Lex understands what follows
is a zodiac sign.

When the valueSelectionStrategy field is set to ORIGINAL_VALUE using the


PutSlotType (p. 319) operation, or if Expand values is selected in the console, if the user says "Tell

184
Amazon Lex Developer Guide
General Guidelines

me the prediction for earth", Amazon Lex infers that "earth" is a ZodiacSign and passes it to your
client application or Lambda functions. You must check that slot values have valid values before using
them in your fulfillment activity.

If you set the valueSelectionStrategy field to TOP_RESOLUTION using the PutSlotType (p. 319)
operation, or if Restrict to slot values and synonyms is selected in the console, the values that are
returned are limited to the values that you defined for the slot type. For example, if the user says "Tell
me the prediction for earth" the value would not be recognized because it is not one of the values
defined for the slot type. When you define synonyms for slot values, they are recognized the same as a
slot value, however, the slot value is returned instead of the synonym.

When Amazon Lex calls a Lambda function or returns the result of a speech interaction with your
client application, the case of the slot values is not guaranteed. For example, if you are eliciting values
for the AMAZON.Movie built-in slot type, and a user says or types "Gone with the wind," Amazon Lex
may return "Gone with the Wind," "gone with the wind," or "Gone With The Wind." In text interactions,
the case of the slot values matches the text entered or the slot value, depending on the value of the
valueResolutionStrategy field.

 
• Amazon Lex does not support the AMAZON.LITERAL built-in slot type that the Alexa Skills Kit
supports. However, Amazon Lex supports creating custom slot types that you can use to implement
this functionality. As mentioned in the previous bullet, you can capture values outside the custom slot
type definition. Add more and diverse enumeration values to boost the automatic speech recognition
(ASR) and natural language understanding (NLU) accuracy.

 
• The AMAZON.DATE and AMAZON.TIME built-in slot types capture both absolute and relative dates and
times. Relative dates and times are resolved in the region where Amazon Lex is processing the request.

For the AMAZON.TIME built-in slot type, if the user doesn't specify that a time is before or after noon,
the time is ambiguous and Amazon Lex will prompt the user again. We recommend prompts that elicit
an absolute time. For example, use a prompt such as "When do you want your pizza delivered? You can
say 6 PM or 6 in the evening."

 
• Providing confusable training data in your bot reduces Amazon Lex's ability to understand user input.
Consider these examples:

Suppose you have two intents (OrderPizza and OrderDrink) in your bot and both are configured
with an "I want to order" utterance. This utterance does not map to a specific intent that Amazon Lex
can learn from while building the language model for the bot at build time. As a result, when a user
inputs this utterance at runtime, Amazon Lex can't pick an intent with a high degree of confidence.

Consider another example where you define a custom intent for getting a confirmation from the user
(for example, MyCustomConfirmationIntent) and configure the intent with the utterances "Yes"
and "No." Note that Amazon Lex also has a language model for understanding user confirmations.
This can create conflicting situation. When the user responds with a "Yes," does this mean that this is a
confirmation for the ongoing intent or that the user is requesting the custom intent that you created?
185
Amazon Lex Developer Guide
Limits

In general, the sample utterances you provide should map to a specific intent and, optionally, to
specific slot values.

 
• The runtime API operations PostContent (p. 327) and PostText (p. 335) take a user ID as the
required parameter. Developers can set this to any value that meets the constraints described in the
API. We recommend you don't use this parameter to send any confidential information such as user
logins, emails, or social security numbers. This ID is primarily used to uniquely identify conversation
with a bot (there can be multiple users ordering pizza).

 
• If your client application uses Amazon Cognito for authentication, you might use the Amazon Cognito
user ID as Amazon Lex user ID. Note that any Lambda function configured for your bot must have
its own authentication mechanism to identify the user on whose behalf Amazon Lex is invoking the
Lambda function.

 
• We encourage you to define an intent that captures a user's intention to discontinue the conversation.
For example, you can define an intent (NothingIntent) with sample utterances ("I don't want
anything", "exit", "bye bye"), no slots, and no Lambda function configured as a code hook. This lets
users gracefully close a conversation.

Limits
This section describes current limits in Amazon Lex. These limits are grouped by categories.

Topics
• General Limits (p. 186)
• Runtime Service Limits (p. 186)
• Model Building Limits (p. 187)

General Limits
For a list of AWS Regions where Amazon Lex is available, see AWS Regions and Endpoints in the Amazon
Web Services General Reference.

Currently, Amazon Lex supports only US English language. That is, Amazon Lex trains your bots to
understand only US English.

Runtime Service Limits


In addition to the limits described in the API reference, note the following:

API Limits
• Speech input to the PostContent (p. 327) operation can be up to 15 seconds long.

186
Amazon Lex Developer Guide
Model Building Limits

 
• In both the runtime API operations PostContent (p. 327) and PostText (p. 335), the input text size
can be up to 1024 Unicode characters.

 
• The maximum size of PostContent headers is 16 KB. The maximum size of request and session
headers combined is 12 KB.

 
• The maximum input size to a Lambda function is 12 KB. The maximum output size is 25 KB, of which
12 KB can be session attributes.

Using the $LATEST version


• The $LATEST version of your bot should only be used for manual testing. Amazon Lex limits the
number of runtime requests that you can make to the $LATEST version of the bot.

 
• When you update the $LATEST version of the bot, Amazon Lex terminates any in-progress
conversations for any client application using the $LATEST version of the bot. Generally, you should
not use the $LATEST version of a bot in production because $LATEST version can be updated. You
should publish a version and use it instead.

 
• When you update an alias, Amazon Lex takes a few minutes to pick up the change. When you modify
the $LATEST version of the bot, the change is picked up immediately.

Session Timeout
• The session timeout set when the bot was created determines how long the bot retains conversation
context, such as current user intent and slot data.

 
• After a user starts the conversation with your bot and until the session expires, Amazon Lex uses the
same bot version, even if you update the bot alias to point to another version.

Model Building Limits


Model building refers to creating and managing bots. This includes creating and managing bots, intents,
slot types, slots, and bot channel associations.

Topics
• Bot Limits (p. 188)
• Intent Limits (p. 189)
• Slot Type Limits (p. 190)

187
Amazon Lex Developer Guide
Model Building Limits

Bot Limits
• You configure prompts and statements throughout the model building API. Each of these prompts
or statements can have up to five messages and each message can contain from 1 to 1000 UTF-8
characters.

 
• When using message groups you can define up to five message groups for each message. Each
message group can contain a maximum of five messages, and you are limited to 15 messages in all
message groups.

 
• You can define sample utterances for intents and slots. You can use a maximum of 200,000 characters
for all utterances.

 
• Each slot type can define a maximum of 10,000 values and synonyms. Each bot can contain a
maximum of 50,000 slot type values and synonyms.

 
• Bot, alias, and bot channel association names are case insensitive at the time of creation. If you create
PizzaBot and then try to create pizzaBot, you will get an error. However, when accessing a resource,
the resource names are case sensitive, you must specify PizzaBot and not pizzaBot. These names
must be between 2 and 50 ASCII characters.

 
• The maximum number of versions you can publish for all resource types is 100. Note that there is no
versioning for aliases.

 
• Within a bot, intent names and slot names must be unique, you can't have an intent and a slot by the
same name.

 
• You can create a bot that is configured to support multiple intents. If two intents have a slot by the
same name, then the corresponding slot type must be the same.

For example, suppose you create a bot to support two intents (OrderPizza and OrderDrink). If both
these intents have the size slot, then the slot type must be the same in both places.

In addition, the sample utterances you provide for a slot in one of the intents applies to a slot with the
same name in other intents.

 
• You can associate a maximum of 100 intents with a bot.

 
• When you create a bot, you specify a session timeout. The session timeout can be between one minute
and one day. The default is five minutes.

 
• You can create up to five aliases for a bot.

188
Amazon Lex Developer Guide
Model Building Limits

 
• You can create up to 100 bots per AWS account.

 
• You cannot create multiple intents that extend from the same built-in intent.

Intent Limits
• Intent and slot names are case insensitive at the time of creation. That is, if you create OrderPizza
intent and then again try to create another orderPizza intent, you will get an error. However,
when accessing these resources, the resource names are case sensitive, specify OrderPizza and not
orderPizza. These names must be between 1 and 100 ASCII characters.

 
• An intent can have up to 1,500 sample utterances. A minimum of one sample utterance is required.
Each sample utterance can be up to 200 UTF-8 characters long. You can use up to 200,000 characters
for all intent and slot utterances in a bot. A sample utterance for an intent:
• Can refer to zero or more slot names.
• Can refer to a slot name only once.

For example:

I want a pizza
I want a {pizzaSize} pizza
I want a {pizzaSize} {pizzaTopping} pizza

 
• Although each intent supports up to 1,500 utterances, if you use fewer utterances Amazon Lex may
have a better ability to recognize inputs outside your provided set.

 
• You can create up to five message groups for each message in an intent. There can be a total of 15
messages in all message groups for a message.

 
• The console can only create message groups for the conclusionStatement and followUpPrompt
messages. You can create message groups for any other message using the Amazon Lex API.

 
• Each slot can have up to 10 sample utterances. Each sample utterance must refer to the slot name
exactly once. For example:

{pizzaSize} please

 
• Each bot can have a maximum of 200,000 characters for intent and slot utterances combined.

 
• You cannot provide utterances for intents that extend from built-in intents. For all other intents you
must provide at least one sample utterance. Intents contain slots, but the slot level sample utterances
are optional.

189
Amazon Lex Developer Guide
Model Building Limits

 
• Built-in intents
• Currently, Amazon Lex does not support slot elicitation for built-in intents. You cannot create
Lambda functions to return the ElicitSlot directive in the response with an intent that is derived
from built-in intents. For more information, see Response Format (p. 104).
• The service does not support adding sample utterances to built-in intents. Similarly, you cannot add
or remove slots to built-in intents.

 
• You can create up to 1,000 intents per AWS account. You can create up to 100 slots in an intent.

Slot Type Limits


• Slot type names are case insensitive at the time of creation. If you create the PizzaSize slot type and
then again try to create the pizzaSize slot type, you will get an error. However, when accessing these
resources, the resource names are case sensitive (you must specify PizzaSize and not pizzaSize).
Names must be between 1 and 100 ASCII characters.

 
• A custom slot type you create can have a maximum of 10,000 enumeration values and synonyms. Each
value can be up to 140 UTF-8 characters long. The enumeration values and synonyms cannot contain
duplicates.

 
• For a slot type value, where appropriate, specify both upper and lower case. For example, for a slot
type called Procedure, if value is MRI, specify both "MRI" and "mri" as values.

 
• Built-in slot types – Currently, Amazon Lex doesn't support adding enumeration values or synonyms
for the built-in slot types.

190
Amazon Lex Developer Guide
Authentication

Authentication and Access Control


for Amazon Lex
Access to Amazon Lex requires credentials that AWS can use to authenticate your requests. Those
credentials must have permissions to access AWS resources, such as an Amazon Lex chatbot or an
Amazon Lex slot type. The following sections provide details on how you can use AWS Identity and
Access Management (IAM) and Amazon Lex to help secure your resources by controlling who can access
them.

• Authentication (p. 191)


• Access Control (p. 192)

Authentication
You can access AWS as any of the following types of identities:

• AWS account root user – When you first create an AWS account, you begin with a single sign-in
identity that has complete access to all AWS services and resources in the account. This identity is
called the AWS account root user and is accessed by signing in with the email address and password
that you used to create the account. We strongly recommend that you do not use the root user for
your everyday tasks, even the administrative ones. Instead, adhere to the best practice of using the
root user only to create your first IAM user. Then securely lock away the root user credentials and use
them to perform only a few account and service management tasks.
• IAM user – An IAM user is an identity within your AWS account that has specific custom permissions
(for example, permissions to create a bot in Amazon Lex). You can use an IAM user name and password
to sign in to secure AWS webpages like the AWS Management Console, AWS Discussion Forums, or the
AWS Support Center.

In addition to a user name and password, you can also generate access keys for each user. You can
use these keys when you access AWS services programmatically, either through one of the several
SDKs or by using the AWS Command Line Interface (CLI). The SDK and CLI tools use the access keys
to cryptographically sign your request. If you don’t use AWS tools, you must sign the request yourself.
Amazon Lex supports Signature Version 4, a protocol for authenticating inbound API requests. For
more information about authenticating requests, see Signature Version 4 Signing Process in the AWS
General Reference.

 
• IAM role – An IAM role is an IAM identity that you can create in your account that has specific
permissions. It is similar to an IAM user, but it is not associated with a specific person. An IAM role
enables you to obtain temporary access keys that can be used to access AWS services and resources.
IAM roles with temporary credentials are useful in the following situations:

 
• Federated user access – Instead of creating an IAM user, you can use existing user identities from
AWS Directory Service, your enterprise user directory, or a web identity provider. These are known as

191
Amazon Lex Developer Guide
Access Control

federated users. AWS assigns a role to a federated user when access is requested through an identity
provider. For more information about federated users, see Federated Users and Roles in the IAM User
Guide.

 
• AWS service access – You can use an IAM role in your account to grant an AWS service permissions
to access your account’s resources. For example, you can create a role that allows Amazon Redshift
to access an Amazon S3 bucket on your behalf and then load data from that bucket into an Amazon
Redshift cluster. For more information, see Creating a Role to Delegate Permissions to an AWS
Service in the IAM User Guide.

 
• Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials
for applications that are running on an EC2 instance and making AWS API requests. This is preferable
to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make
it available to all of its applications, you create an instance profile that is attached to the instance.
An instance profile contains the role and enables programs that are running on the EC2 instance
to get temporary credentials. For more information, see Using an IAM Role to Grant Permissions to
Applications Running on Amazon EC2 Instances in the IAM User Guide.

Access Control
You can have valid credentials to authenticate your requests, but unless you have permissions you cannot
create or access Amazon Lex resources. For example, you must have permissions to create an Amazon Lex
bot.

The following sections describe how to manage permissions for Amazon Lex. We recommend that you
read the overview first.

• Overview of Managing Access Permissions to Your Amazon Lex Resources (p. 192)
• Using Identity-Based Policies (IAM Policies) for Amazon Lex (p. 196)

Overview of Managing Access Permissions to Your


Amazon Lex Resources
Every AWS resource is owned by an AWS account, and permissions to create or access a resource are
governed by permissions policies. An account administrator can attach permissions policies to IAM
identities (that is, users, groups, and roles), and some services (such as AWS Lambda) also support
attaching permissions policies to resources.
Note
An account administrator (or administrator user) is a user with administrator privileges. For more
information, see IAM Best Practices in the IAM User Guide.

When granting permissions, you decide who is getting the permissions, the resources they get
permissions for, and the specific actions that you want to allow on those resources.

Topics
• Amazon Lex Resources and Operations (p. 193)
• Understanding Resource Ownership (p. 193)
• Managing Access to Resources (p. 193)

192
Amazon Lex Developer Guide
Amazon Lex Resources and Operations

• Specifying Policy Elements: Actions, Effects, and Principals (p. 194)


• Specifying Conditions in a Policy (p. 195)

Amazon Lex Resources and Operations


In Amazon Lex, the primary resource is a bot. Amazon Lex also supports additional resource types, the
intent, the slot type, the alias, and the bot channel association. Aliases and bot channel associations
are referred to as subresources. For Amazon Lex, you can create subresources only in the context of an
existing bot.

These resources and subresources have unique Amazon Resource Names (ARNs) associated with them as
shown in the following table.

Amazon Lex provides a set of operations to work with Amazon Lex resources. For a list of available
operations, see Amazon Lex Actions (p. 202).

Understanding Resource Ownership


The AWS account owns the resources that are created in the account, regardless of who created the
resources. Specifically, the resource owner is the AWS account of the principal entity (that is, the root
account, an IAM user, or an IAM role) that authenticates the resource creation request. The following
examples illustrate how this works:

• If you use the root account credentials of your AWS account to create a bot, your AWS account is the
owner of the resource (in Amazon Lex, the resource is the bot).
• If you create an IAM user in your AWS account and grant permissions to create a bot to that user, the
user can create a bot. However, your AWS account, to which the user belongs, owns the bot resource.
• If you create an IAM role in your AWS account with permissions to create a bot, anyone who can
assume the role can create a bot. Your AWS account, to which the role belongs, owns the bot resource.

Managing Access to Resources


A permissions policy describes who has access to what. The following section explains the available
options for creating permissions policies.
Note
This section discusses using IAM in the context of Amazon Lex. It doesn't provide detailed
information about the IAM service. For complete IAM documentation, see What Is IAM? in the
IAM User Guide. For information about IAM policy syntax and descriptions, see AWS IAM Policy
Reference in the IAM User Guide.

Policies attached to an IAM identity are referred to as identity-based policies (IAM policies) and policies
attached to a resource are referred to as resource-based policies. Amazon Lex supports only identity-
based policies (IAM policies).

Topics
• Identity-Based Policies (IAM Policies) (p. 193)
• Resource-Based Policies (p. 194)

Identity-Based Policies (IAM Policies)


You can attach policies to IAM identities. For example, you can do the following:

193
Amazon Lex Developer Guide
Specifying Policy Elements: Actions, Effects, and Principals

• Attach a permissions policy to a user or a group in your account – To grant a user or a group of users
permissions to create a Amazon Lex resource, such as a bot, you can attach a permissions policy to a
user or group that the user belongs to.
• Attach a permissions policy to a role (grant cross-account permissions) – To grant cross-account
permissions, you can attach an identity-based permissions policy to an IAM role. For example, the
administrator in Account A can create a role to grant cross-account permissions to another AWS
account (for example, Account B) or an AWS service as follows:
1. Account A administrator creates an IAM role and attaches a permissions policy to the role that
grants permissions on resources in Account A.
2. Account A administrator attaches a trust policy to the role identifying Account B as the principal
who can assume the role.
3. Account B administrator can then delegate permissions to assume the role to any users in Account
B. Doing this allows users in Account B to create or access resources in Account A. If you want to
grant an AWS service permissions to assume the role, the principal in the trust policy can also be an
AWS service principal.

For more information about using IAM to delegate permissions, see Access Management in the IAM
User Guide.

The following is an example policy that allows the user to perform the PutBot action for your AWS
account.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lex:PutBot"],
"Resource": [
"*"
]
}
]
}

For more information about using identity-based policies with Amazon Lex, see Using Identity-Based
Policies (IAM Policies) for Amazon Lex (p. 196). For more information about users, groups, roles, and
permissions, see Identities (Users, Groups, and Roles) in the IAM User Guide.

Resource-Based Policies
Other services, such as Lambda, support resource-based permissions policies. For example, you can
attach a policy to an S3 bucket to manage access permissions to that bucket. Amazon Lex doesn't
support resource-based policies. However, it does use resource-based policies to access Lambda and
Amazon Polly services. 

Specifying Policy Elements: Actions, Effects, and


Principals
For each Amazon Lex resource (see Amazon Lex Resources and Operations (p. 193)), the service defines
a set of API operations (see Actions (p. 202)). To grant permissions for these API operations, Amazon
Lex defines a set of actions that you can specify in a policy. For example, for the Amazon Lex Intent
resource, the following actions are defined: CreateIntent and CreateIntentVersion. Performing
an API operation can require permissions for more than one action.

194
Amazon Lex Developer Guide
Specifying Conditions in a Policy

The following are the most basic policy elements:

• Resource – In a policy, you use an Amazon Resource Name (ARN) to identify the resource to which the
policy applies. For more information, see Amazon Lex Resources and Operations (p. 193).
• Action – You use action keywords to identify resource operations that you want to allow or deny. For
example, depending on the specified Effect, lex:bBot either allows or denies the user permissions
to perform the Amazon Lex CreateBot operation.
• Effect – You specify the effect of the action that occurs when the user requests the specific action
—this can be either allow or deny. If you don't explicitly grant access to (allow) a resource, access is
implicitly denied. You can also explicitly deny access to a resource. You might do this to make sure that
a user cannot access the resource, even if a different policy grants access.
• Principal – In identity-based policies (IAM policies), the user that the policy is attached to is the
implicit principal. For resource-based policies, you specify the user, account, service, or other entity
that you want to receive permissions. This applies to resource-based policies only. Amazon Lex doesn't
support resource-based policies.

To learn more about IAM policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User
Guide.

For a table showing all of the Amazon Lex API actions, see Amazon Lex API Permissions: Actions,
Resources, and Conditions Reference (p. 201).

Specifying Conditions in a Policy


When you grant permissions, you use the IAM policy language to specify the conditions under which a
policy should take effect. For example, you might want a policy to be applied only after a specific date.
For more information about specifying conditions in a policy language, see Condition in the IAM User
Guide.

AWS provides a set of predefined condition keys for all AWS services that support IAM for access control.
For example, you can use the aws:userid condition key to require a specific AWS ID when requesting an
action. For more information and a complete list of AWS-wide keys, see Available Keys for Conditions in
the IAM User Guide.
Note
Condition keys are case sensitive.

Amazon Lex provides additional condition keys that you can include in Condition elements in an IAM
permissions policy. The following table shows the Amazon Lex condition keys that apply to Amazon Lex
resources.

Example Policy: Using Condition Keys


The following example shows how to use condition keys in Amazon Lex IAM permissions policies.

Example 1: Grant Permission to Create Bots Using the OrderPizza Intent

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lex:PutBot"
"Resource": [
" *"

195
Amazon Lex Developer Guide
Using Identity-Based Policies (IAM Policies) for Amazon Lex

],
"Condition": {
"ForAllValues:StringLike": {
"lex:associatedIntents": [
"OrderPizza"
]
}
}
}
]
}

Using Identity-Based Policies (IAM Policies) for


Amazon Lex
This topic provides examples of identity-based policies that demonstrate how an account administrator
can attach permissions policies to IAM identities (that is, users, groups, and roles) and thereby grant
permissions to perform operations on Amazon Lex resources.
Important
Before you proceed, we recommend that you review Overview of Managing Access Permissions
to Your Amazon Lex Resources (p. 192).

The sections in this topic cover the following:

• Permissions Required to Use the Amazon Lex Console (p. 197)


• AWS Managed (Predefined) Policies for Amazon Lex (p. 199)
• Examples of Customer Managed Policies (p. 199)

The following is an example of a permissions policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lex:PostText"
],
"Resource": [
"arn:aws:lex:us-east-1:account-id:bot:OrderPizza:*"
]
}
]
}

The policy has one statement that grants permission to use the PostText action with the OrderPizza
bot. The resource specifies a wildcard character (*) to give permission to any alias of the OrderPizza
bot.

The policy doesn't specify the Principal element because you don't specify the principal who gets
the permission in an identity-based policy. When you attach a policy to a user, the user is the implicit
principal. When you attach a permissions policy to an IAM role, the principal identified in the role's trust
policy gets the permissions.

196
Amazon Lex Developer Guide
Permissions Required to Use the Amazon Lex Console

For a table showing all of the Amazon Lex API actions and the resources that they apply to, see Amazon
Lex API Permissions: Actions, Resources, and Conditions Reference (p. 201).

Permissions Required to Use the Amazon Lex Console


The permissions reference table lists the Amazon Lex API operations and shows the required permissions
for each operation. For more information about Amazon Lex API operations, see Amazon Lex API
Permissions: Actions, Resources, and Conditions Reference (p. 201).

To use the Amazon Lex console, you need to grant permissions for additional actions as shown in the
following permissions policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:GetMetricStatistics",
"cloudwatch:DescribeAlarms",
"cloudwatch:DescribeAlarmsForMetric",
"kms:DescribeKey",
"kms:ListAliases",
"lambda:GetPolicy",
"lambda:ListFunctions",
"lex:*",
"polly:DescribeVoices",
"polly:SynthesizeSpeech"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:RemovePermission"
],
"Resource": "*",
"Condition": {
"StringLike": {
"lambda:Principal": "lex.amazonaws.com"
}
}
},
{
"Effect": "Allow",
"Action": [
"iam:GetRole",
"iam:DeleteRole"
],
"Resource": [
"arn:aws:iam::*:role/aws-service-role/lex.amazonaws.com/
AWSServiceRoleForLexBots",
"arn:aws:iam::*:role/aws-service-role/channels.lex.amazonaws.com/
AWSServiceRoleForLexChannels"
]
},
{
"Effect": "Allow",
"Action": [
"iam:CreateServiceLinkedRole"

197
Amazon Lex Developer Guide
Permissions Required to Use the Amazon Lex Console

],
"Resource": [
"arn:aws:iam::*:role/aws-service-role/lex.amazonaws.com/
AWSServiceRoleForLexBots"
],
"Condition": {
"StringLike": {
"iam:AWSServiceName": "lex.amazonaws.com"
}
}
},
{
"Effect": "Allow",
"Action": [
"iam:DetachRolePolicy"
],
"Resource": [
"arn:aws:iam::*:role/aws-service-role/lex.amazonaws.com/
AWSServiceRoleForLexBots"
],
"Condition": {
"StringLike": {
"iam:PolicyArn": "arn:aws:iam::aws:policy/aws-service-role/
AmazonLexBotPolicy"
}
}
},
{
"Effect": "Allow",
"Action": [
"iam:CreateServiceLinkedRole"
],
"Resource": [
"arn:aws:iam::*:role/aws-service-role/channels.lex.amazonaws.com/
AWSServiceRoleForLexChannels"
],
"Condition": {
"StringLike": {
"iam:AWSServiceName": "channels.lex.amazonaws.com"
}
}
},
{
"Effect": "Allow",
"Action": [
"iam:DetachRolePolicy"
],
"Resource": [
"arn:aws:iam::*:role/aws-service-role/channels.lex.amazonaws.com/
AWSServiceRoleForLexChannels"
],
"Condition": {
"StringLike": {
"iam:PolicyArn": "arn:aws:iam::aws:policy/aws-service-role/
LexChannelPolicy"
}
}
}
]
}

The Amazon Lex console needs these additional permissions for the following reasons:

• cloudwatch permissions to view performance and monitoring information in the console.

198
Amazon Lex Developer Guide
AWS Managed (Predefined) Policies for Amazon Lex

• iam actions to assume IAM roles for making calls to Lambda functions and processing data for a bot
channel association.
• kms actions to manage the AWS Key Management Service keys used to encrypt data when creating a
bot channel association.
• lambda actions to display Lambda functions that your bot can use, and to grant Lex the necessary
permissions for your bot to invoke these functions.
• lex actions so that the console can display Amazon Lex resources in the account.
• polly actions so that the console can display Amazon Polly voices and so that it can translate text to
speech.
• iam actions so that the console can manage server-linked roles that grant permission to use other
AWS resources.

AWS Managed (Predefined) Policies for Amazon Lex


AWS addresses many common use cases by providing standalone IAM policies that are created and
administered by AWS. Managed policies grant necessary permissions for common use cases so you can
avoid having to investigate which permissions are needed. For more information, see AWS Managed
Policies in the IAM User Guide.

The following AWS managed policies, which you can attach to users in your account, are specific to
Amazon Lex:

• ReadOnly — Grants read-only access to Amazon Lex resources.


• RunBotsOnly — Grants access to run Amazon Lex conversational bots.
• FullAccess — Grants full access to create, read, update, delete, and run all Amazon Lex resources.
Grants access to associate Lambda functions whose name starts with AmazonLex with Amazon Lex
intents.

Note
You can review these permissions policies by signing in to the IAM console and searching for
specific policies.

You can also create your own custom IAM policies to allow permissions for Amazon Lex API actions. You
can attach these custom policies to the IAM users or groups that require those permissions.

Examples of Customer Managed Policies


In this section, we provide examples of user policies that grant permissions for various Amazon Lex
actions. These policies work with the AWS SDKs or the AWS command line interface (AWS ). When you
use the console, you need to grant additional permissions specific to the console, which is discussed in
Permissions Required to Use the Amazon Lex Console (p. 197).
Note
All examples use the us-east-1 Region and contain fictitious account IDs.

Examples
• Example 1: Allow a User to Delete Any Bot (p. 200)
• Example 2: Allow a User to Update a Specific Bot (p. 200)
• Example 3: Allow a User to Manage a Specific Bot (p. 200)

199
Amazon Lex Developer Guide
Examples of Customer Managed Policies

Example 1: Allow a User to Delete Any Bot


The following permissions policy grants the user permissions to delete any bot that exists in the us-
east-1 Region.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lex:DeleteBot"
"Resource": [
"*"
]
}
]
}

Example 2: Allow a User to Update a Specific Bot


The following policy grants the user permissions to update a specific bot in the us-east-1 Region, in
this case, the bot named "PizzaBot."

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lex:PutBot"
"Resource": [
"arn:aws:lex:us-east-1:account-id:bot:PizzaBot:$LATEST"
]
}
]
}

Example 3: Allow a User to Manage a Specific Bot


The following permissions policy grants the user permissions to build and test a pizza ordering, and can
only use the OrderPizza intent and Toppings slot type when editing the bot in the us-east-1 region.
The policy uses the lex:associatedIntents and lex:associatedSlotType to limit the intent and
slot types that the user can use for this bot.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lex:Create*Version",
"lex:Post*",
"lex:Put*",
"lex:Delete*"
],
"Resource": [

200
Amazon Lex Developer Guide
Amazon Lex API Permissions Reference

"arn:aws:lex:us-east-1:*:bot:PizzaBot:*",
"arn:aws:lex:us-east-1:*:intent:OrderPizza:*",
"arn:aws:lex:us-east-1:*:slottype:Toppings:*"
],
"Condition": {
"ForAllValues:StringEqualsIfExists": {
"lex:associatedIntents": [
"OrderPizza"
],
"lex:associatedSlotTypes": [
"Toppings"
]
}
}
},
{
"Effect": "Allow",
"Action": [
"lex:Get*"
],
"Resource": [
"arn:aws:lex:us-east-1:*:bot:*",
"arn:aws:lex:us-east-1:*:intent:*",
"arn:aws:lex:us-east-1:*:slottype:*"
]
}
]
}

Amazon Lex API Permissions: Actions, Resources,


and Conditions Reference
Use the following table as a reference when setting up Access Control (p. 192) and writing a
permissions policy that you can attach to an IAM identity (an identity-based policy). The list includes
each Amazon Lex API operation, the corresponding action for which you can grant permissions to
perform the action, and the AWS resource for which you can grant the permissions. You specify the
actions in the policy's Action field, and you specify the resource value in the policy's Resource field.

To express conditions, you can use AWS-wide condition keys in your Amazon Lex policies. For a complete
list of AWS-wide keys, see Available Keys in the IAM User Guide.
Note
To specify an action, use the lex: prefix followed by the API operation name, for example,
lex:PostText.
Note
The GetExport function checks permission at the bot level and, if authorized, exports all
relevant intent and slot type information associated with the specified bot. GetExport does not
check intent-level and slot type-level permissions.

201
Amazon Lex Developer Guide
Actions

API Reference
This section provides documentation for the Amazon Lex API operations. For a list of AWS Regions where
Amazon Lex is available, see AWS Regions and Endpoints in the Amazon Web Services General Reference.

Topics

• Actions (p. 202)


• Data Types (p. 340)

Actions
The following actions are supported by Amazon Lex Model Building Service:

• CreateBotVersion (p. 205)


• CreateIntentVersion (p. 210)
• CreateSlotTypeVersion (p. 216)
• DeleteBot (p. 220)
• DeleteBotAlias (p. 222)
• DeleteBotChannelAssociation (p. 224)
• DeleteBotVersion (p. 226)
• DeleteIntent (p. 228)
• DeleteIntentVersion (p. 230)
• DeleteSlotType (p. 232)
• DeleteSlotTypeVersion (p. 234)
• DeleteUtterances (p. 236)
• GetBot (p. 238)
• GetBotAlias (p. 243)
• GetBotAliases (p. 246)
• GetBotChannelAssociation (p. 249)
• GetBotChannelAssociations (p. 253)
• GetBots (p. 256)
• GetBotVersions (p. 259)
• GetBuiltinIntent (p. 262)
• GetBuiltinIntents (p. 264)
• GetBuiltinSlotTypes (p. 266)
• GetExport (p. 268)
• GetImport (p. 271)
• GetIntent (p. 274)
• GetIntents (p. 279)
• GetIntentVersions (p. 282)
• GetSlotType (p. 285)
• GetSlotTypes (p. 288)
• GetSlotTypeVersions (p. 291)

202
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• GetUtterancesView (p. 294)


• PutBot (p. 297)
• PutBotAlias (p. 305)
• PutIntent (p. 309)
• PutSlotType (p. 319)
• StartImport (p. 324)

The following actions are supported by Amazon Lex Runtime Service:

• PostContent (p. 327)


• PostText (p. 335)

Amazon Lex Model Building Service


The following actions are supported by Amazon Lex Model Building Service:

• CreateBotVersion (p. 205)


• CreateIntentVersion (p. 210)
• CreateSlotTypeVersion (p. 216)
• DeleteBot (p. 220)
• DeleteBotAlias (p. 222)
• DeleteBotChannelAssociation (p. 224)
• DeleteBotVersion (p. 226)
• DeleteIntent (p. 228)
• DeleteIntentVersion (p. 230)
• DeleteSlotType (p. 232)
• DeleteSlotTypeVersion (p. 234)
• DeleteUtterances (p. 236)
• GetBot (p. 238)
• GetBotAlias (p. 243)
• GetBotAliases (p. 246)
• GetBotChannelAssociation (p. 249)
• GetBotChannelAssociations (p. 253)
• GetBots (p. 256)
• GetBotVersions (p. 259)
• GetBuiltinIntent (p. 262)
• GetBuiltinIntents (p. 264)
• GetBuiltinSlotTypes (p. 266)
• GetExport (p. 268)
• GetImport (p. 271)
• GetIntent (p. 274)
• GetIntents (p. 279)
• GetIntentVersions (p. 282)
• GetSlotType (p. 285)
• GetSlotTypes (p. 288)
• GetSlotTypeVersions (p. 291)

203
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• GetUtterancesView (p. 294)


• PutBot (p. 297)
• PutBotAlias (p. 305)
• PutIntent (p. 309)
• PutSlotType (p. 319)
• StartImport (p. 324)

204
Amazon Lex Developer Guide
Amazon Lex Model Building Service

CreateBotVersion
Service: Amazon Lex Model Building Service

Creates a new version of the bot based on the $LATEST version. If the $LATEST version of this resource
hasn't changed since you created the last version, Amazon Lex doesn't create a new version. It returns
the last created version.
Note
You can update only the $LATEST version of the bot. You can't update the numbered versions
that you create with the CreateBotVersion operation.

When you create the first version of a bot, Amazon Lex sets the version to 1. Subsequent versions
increment by 1. For more information, see Versioning (p. 97).

This operation requires permission for the lex:CreateBotVersion action.

Request Syntax

POST /bots/name/versions HTTP/1.1


Content-type: application/json

{
"checksum": "string"
}

URI Request Parameters


The request requires the following URI parameters.

name (p. 205)

The name of the bot that you want to create a new version of. The name is case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

checksum (p. 205)

Identifies a specific revision of the $LATEST version of the bot. If you specify a checksum and
the $LATEST version of the bot has a different checksum, a PreconditionFailedException
exception is returned and Amazon Lex doesn't publish a new version. If you don't specify a
checksum, Amazon Lex publishes the $LATEST version.

Type: String

Required: No

Response Syntax

HTTP/1.1 201
Content-type: application/json

205
Amazon Lex Developer Guide
Amazon Lex Model Building Service

{
"abortStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"checksum": "string",
"childDirected": boolean,
"clarificationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"createdDate": number,
"description": "string",
"failureReason": "string",
"idleSessionTTLInSeconds": number,
"intents": [
{
"intentName": "string",
"intentVersion": "string"
}
],
"lastUpdatedDate": number,
"locale": "string",
"name": "string",
"status": "string",
"version": "string",
"voiceId": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service.

abortStatement (p. 205)

The message that Amazon Lex uses to abort a conversation. For more information, see
PutBot (p. 297).

Type: Statement (p. 365) object


checksum (p. 205)

Checksum identifying the version of the bot that was created.

Type: String
childDirected (p. 205)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify
whether your use of Amazon Lex is related to a website, program, or other application that is

206
Amazon Lex Developer Guide
Amazon Lex Model Building Service

directed or targeted, in whole or in part, to children under age 13 and subject to the Children's
Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field.
By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related
to a website, program, or other application that is directed or targeted, in whole or in part, to
children under age 13 and subject to COPPA. By specifying false in the childDirected field, you
confirm that your use of Amazon Lex is not related to a website, program, or other application that
is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may
not specify a default value for the childDirected field that does not accurately reflect whether
your use of Amazon Lex is related to a website, program, or other application that is directed or
targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in
whole or in part, to children under age 13, you must obtain any required verifiable parental consent
under COPPA. For information regarding the use of Amazon Lex in connection with websites,
programs, or other applications that are directed or targeted, in whole or in part, to children under
age 13, see the Amazon Lex FAQ.

Type: Boolean
clarificationPrompt (p. 205)

The message that Amazon Lex uses when it doesn't understand the user's request. For more
information, see PutBot (p. 297).

Type: Prompt (p. 359) object


createdDate (p. 205)

The date when the bot version was created.

Type: Timestamp
description (p. 205)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


failureReason (p. 205)

If status is FAILED, Amazon Lex provides the reason that it failed to build the bot.

Type: String
idleSessionTTLInSeconds (p. 205)

The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. For
more information, see PutBot (p. 297).

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400.


intents (p. 205)

An array of Intent objects. For more information, see PutBot (p. 297).

Type: Array of Intent (p. 355) objects


lastUpdatedDate (p. 205)

The date when the $LATEST version of this bot was updated.

Type: Timestamp

207
Amazon Lex Developer Guide
Amazon Lex Model Building Service

locale (p. 205)

Specifies the target locale for the bot.

Type: String

Valid Values: en-US


name (p. 205)

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
status (p. 205)

When you send a request to create or update a bot, Amazon Lex sets the status response element
to BUILDING. After Amazon Lex builds the bot, it sets status to READY. If Amazon Lex can't
build the bot, it sets status to FAILED. Amazon Lex returns the reason for the failure in the
failureReason response element.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT


version (p. 205)

The version of the bot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+
voiceId (p. 205)

The Amazon Polly voice ID that Amazon Lex uses for voice interactions with the user.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500

208
Amazon Lex Developer Guide
Amazon Lex Model Building Service

LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

209
Amazon Lex Developer Guide
Amazon Lex Model Building Service

CreateIntentVersion
Service: Amazon Lex Model Building Service

Creates a new version of an intent based on the $LATEST version of the intent. If the $LATEST version of
this intent hasn't changed since you last updated it, Amazon Lex doesn't create a new version. It returns
the last version you created.
Note
You can update only the $LATEST version of the intent. You can't update the numbered versions
that you create with the CreateIntentVersion operation.

When you create a version of an intent, Amazon Lex sets the version to 1. Subsequent versions increment
by 1. For more information, see Versioning (p. 97).

This operation requires permissions to perform the lex:CreateIntentVersion action.

Request Syntax

POST /intents/name/versions HTTP/1.1


Content-type: application/json

{
"checksum": "string"
}

URI Request Parameters


The request requires the following URI parameters.

name (p. 210)

The name of the intent that you want to create a new version of. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

checksum (p. 210)

Checksum of the $LATEST version of the intent that should be used to create the new version. If you
specify a checksum and the $LATEST version of the intent has a different checksum, Amazon Lex
returns a PreconditionFailedException exception and doesn't publish a new version. If you
don't specify a checksum, Amazon Lex publishes the $LATEST version.

Type: String

Required: No

Response Syntax

HTTP/1.1 201
Content-type: application/json

210
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"checksum": "string",
"conclusionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"confirmationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"createdDate": number,
"description": "string",
"dialogCodeHook": {
"messageVersion": "string",
"uri": "string"
},
"followUpPrompt": {
"prompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
},
"fulfillmentActivity": {
"codeHook": {
"messageVersion": "string",
"uri": "string"
},
"type": "string"
},
"lastUpdatedDate": number,
"name": "string",
"parentIntentSignature": "string",
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",

211
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"groupNumber": number
}
],
"responseCard": "string"
},
"sampleUtterances": [ "string" ],
"slots": [
{
"description": "string",
"name": "string",
"priority": number,
"responseCard": "string",
"sampleUtterances": [ "string" ],
"slotConstraint": "string",
"slotType": "string",
"slotTypeVersion": "string",
"valueElicitationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
}
],
"version": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service.

checksum (p. 210)

Checksum of the intent version created.

Type: String
conclusionStatement (p. 210)

After the Lambda function specified in the fulfillmentActivity field fulfills the intent, Amazon
Lex conveys this statement to the user.

Type: Statement (p. 365) object


confirmationPrompt (p. 210)

If defined, the prompt that Amazon Lex uses to confirm the user's intent before fulfilling it.

Type: Prompt (p. 359) object


createdDate (p. 210)

The date that the intent was created.

Type: Timestamp
description (p. 210)

A description of the intent.

212
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


dialogCodeHook (p. 210)

If defined, Amazon Lex invokes this Lambda function for each user input.

Type: CodeHook (p. 351) object


followUpPrompt (p. 210)

If defined, Amazon Lex uses this prompt to solicit additional user activity after the intent is fulfilled.

Type: FollowUpPrompt (p. 353) object


fulfillmentActivity (p. 210)

Describes how the intent is fulfilled.

Type: FulfillmentActivity (p. 354) object


lastUpdatedDate (p. 210)

The date that the intent was updated.

Type: Timestamp
name (p. 210)

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
parentIntentSignature (p. 210)

A unique identifier for a built-in intent.

Type: String
rejectionStatement (p. 210)

If the user answers "no" to the question defined in confirmationPrompt, Amazon Lex responds
with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 365) object


sampleUtterances (p. 210)

An array of sample utterances configured for the intent.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200.


slots (p. 210)

An array of slot types that defines the information required to fulfill the intent.

Type: Array of Slot (p. 361) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items.

213
Amazon Lex Developer Guide
Amazon Lex Model Building Service

version (p. 210)

The version number assigned to the new version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3

214
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Python


• AWS SDK for Ruby V2

215
Amazon Lex Developer Guide
Amazon Lex Model Building Service

CreateSlotTypeVersion
Service: Amazon Lex Model Building Service

Creates a new version of a slot type based on the $LATEST version of the specified slot type. If the
$LATEST version of this resource has not changed since the last version that you created, Amazon Lex
doesn't create a new version. It returns the last version that you created.
Note
You can update only the $LATEST version of a slot type. You can't update the numbered
versions that you create with the CreateSlotTypeVersion operation.

When you create a version of a slot type, Amazon Lex sets the version to 1. Subsequent versions
increment by 1. For more information, see Versioning (p. 97).

This operation requires permissions for the lex:CreateSlotTypeVersion action.

Request Syntax

POST /slottypes/name/versions HTTP/1.1


Content-type: application/json

{
"checksum": "string"
}

URI Request Parameters


The request requires the following URI parameters.

name (p. 216)

The name of the slot type that you want to create a new version for. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

checksum (p. 216)

Checksum for the $LATEST version of the slot type that you want to publish. If you specify a
checksum and the $LATEST version of the slot type has a different checksum, Amazon Lex returns
a PreconditionFailedException exception and doesn't publish the new version. If you don't
specify a checksum, Amazon Lex publishes the $LATEST version.

Type: String

Required: No

Response Syntax

HTTP/1.1 201
Content-type: application/json

216
Amazon Lex Developer Guide
Amazon Lex Model Building Service

{
"checksum": "string",
"createdDate": number,
"description": "string",
"enumerationValues": [
{
"synonyms": [ "string" ],
"value": "string"
}
],
"lastUpdatedDate": number,
"name": "string",
"valueSelectionStrategy": "string",
"version": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service.

checksum (p. 216)

Checksum of the $LATEST version of the slot type.

Type: String
createdDate (p. 216)

The date that the slot type was created.

Type: Timestamp
description (p. 216)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


enumerationValues (p. 216)

A list of EnumerationValue objects that defines the values that the slot type can take.

Type: Array of EnumerationValue (p. 352) objects

Array Members: Minimum number of 1 item. Maximum number of 10000 items.


lastUpdatedDate (p. 216)

The date that the slot type was updated. When you create a resource, the creation date and last
update date are the same.

Type: Timestamp
name (p. 216)

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

217
Amazon Lex Developer Guide
Amazon Lex Model Building Service

valueSelectionStrategy (p. 216)

The strategy that Amazon Lex uses to determine the value of the slot. For more information, see
PutSlotType (p. 319).

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION


version (p. 216)

The version assigned to the new slot type version.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface

218
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for .NET


• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

219
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteBot
Service: Amazon Lex Model Building Service

Deletes all versions of the bot, including the $LATEST version. To delete a specific version of the bot, use
the DeleteBotVersion (p. 226) operation. The DeleteBot operation doesn't immediately remove the
bot schema. Instead, it is marked for deletion and removed later.

Amazon Lex stores utterances indefinitely for improving the ability of your bot to respond to user
inputs. These utterances are not removed when the bot is deleted. To remove the utterances, use the
DeleteUtterances (p. 236) operation.

If a bot has an alias, you can't delete it. Instead, the DeleteBot operation returns a
ResourceInUseException exception that includes a reference to the alias that refers to the bot.
To remove the reference to the bot, delete the alias. If you get the same exception again, delete the
referring alias until the DeleteBot operation is successful.

This operation requires permissions for the lex:DeleteBot action.

Request Syntax

DELETE /bots/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 220)

The name of the bot. The name is case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

220
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

221
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteBotAlias
Service: Amazon Lex Model Building Service

Deletes an alias for the specified bot.

You can't delete an alias that is used in the association between a bot and a messaging channel. If an
alias is used in a channel association, the DeleteBot operation returns a ResourceInUseException
exception that includes a reference to the channel association that refers to the bot. You can remove the
reference to the alias by deleting the channel association. If you get the same exception again, delete the
referring association until the DeleteBotAlias operation is successful.

Request Syntax

DELETE /bots/botName/aliases/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botName (p. 222)

The name of the bot that the alias points to.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
name (p. 222)

The name of the alias to delete. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

222
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

223
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteBotChannelAssociation
Service: Amazon Lex Model Building Service

Deletes the association between an Amazon Lex bot and a messaging platform.

This operation requires permission for the lex:DeleteBotChannelAssociation action.

Request Syntax

DELETE /bots/botName/aliases/aliasName/channels/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botAlias (p. 224)

An alias that points to the specific version of the Amazon Lex bot to which this association is being
made.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
botName (p. 224)

The name of the Amazon Lex bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
name (p. 224)

The name of the association. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

224
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

225
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteBotVersion
Service: Amazon Lex Model Building Service

Deletes a specific version of a bot. To delete all versions of a bot, use the DeleteBot (p. 220) operation.

This operation requires permissions for the lex:DeleteBotVersion action.

Request Syntax

DELETE /bots/name/versions/version HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 226)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
version (p. 226)

The version of the bot to delete. You cannot delete the $LATEST version of the bot. To delete the
$LATEST version, use the DeleteBot (p. 220) operation.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409

226
Amazon Lex Developer Guide
Amazon Lex Model Building Service

InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

227
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteIntent
Service: Amazon Lex Model Building Service

Deletes all versions of the intent, including the $LATEST version. To delete a specific version of the
intent, use the DeleteIntentVersion (p. 230) operation.

You can delete a version of an intent only if it is not referenced. To delete an intent that is referred to in
one or more bots (see Amazon Lex: How It Works (p. 3)), you must remove those references first.
Note
If you get the ResourceInUseException exception, it provides an example reference that
shows where the intent is referenced. To remove the reference to the intent, either update the
bot or delete it. If you get the same exception when you attempt to delete the intent again,
repeat until the intent has no references and the call to DeleteIntent is successful.

This operation requires permission for the lex:DeleteIntent action.

Request Syntax

DELETE /intents/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 228)

The name of the intent. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

228
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

229
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteIntentVersion
Service: Amazon Lex Model Building Service

Deletes a specific version of an intent. To delete all versions of a intent, use the DeleteIntent (p. 228)
operation.

This operation requires permissions for the lex:DeleteIntentVersion action.

Request Syntax

DELETE /intents/name/versions/version HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 230)

The name of the intent.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
version (p. 230)

The version of the intent to delete. You cannot delete the $LATEST version of the intent. To delete
the $LATEST version, use the DeleteIntent (p. 228) operation.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

230
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

231
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteSlotType
Service: Amazon Lex Model Building Service

Deletes all versions of the slot type, including the $LATEST version. To delete a specific version of the
slot type, use the DeleteSlotTypeVersion (p. 234) operation.

You can delete a version of a slot type only if it is not referenced. To delete a slot type that is referred to
in one or more intents, you must remove those references first.
Note
If you get the ResourceInUseException exception, the exception provides an example
reference that shows the intent where the slot type is referenced. To remove the reference to
the slot type, either update the intent or delete it. If you get the same exception when you
attempt to delete the slot type again, repeat until the slot type has no references and the
DeleteSlotType call is successful.

This operation requires permission for the lex:DeleteSlotType action.

Request Syntax

DELETE /slottypes/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 232)

The name of the slot type. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

232
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

233
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteSlotTypeVersion
Service: Amazon Lex Model Building Service

Deletes a specific version of a slot type. To delete all versions of a slot type, use the
DeleteSlotType (p. 232) operation.

This operation requires permissions for the lex:DeleteSlotTypeVersion action.

Request Syntax

DELETE /slottypes/name/version/version HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 234)

The name of the slot type.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
version (p. 234)

The version of the slot type to delete. You cannot delete the $LATEST version of the slot type. To
delete the $LATEST version, use the DeleteSlotType (p. 232) operation.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

234
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404


ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this
information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

235
Amazon Lex Developer Guide
Amazon Lex Model Building Service

DeleteUtterances
Service: Amazon Lex Model Building Service

Deletes stored utterances.

Amazon Lex stores the utterances that users send to your bot. Utterances are stored for 15 days for use
with the GetUtterancesView (p. 294) operation, and then stored indefinitely for use in improving the
ability of your bot to respond to user input.

Use the DeleteUtterances operation to manually delete stored utterances for a specific user. When
you use the DeleteUtterances operation, utterances stored for improving your bot's ability to
respond to user input are deleted immediately. Utterances stored for use with the GetUtterancesView
operation are deleted after 15 days.

This operation requires permissions for the lex:DeleteUtterances action.

Request Syntax

DELETE /bots/botName/utterances/userId HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botName (p. 236)

The name of the bot that stored the utterances.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
userId (p. 236)

The unique identifier for the user that made the utterances. This is the user ID that was sent in the
PostContent or PostText operation request that contained the utterance.

Length Constraints: Minimum length of 2. Maximum length of 100.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements
If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

236
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

237
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBot
Service: Amazon Lex Model Building Service

Returns metadata information for a specific bot. You must provide the bot name and the bot version or
alias.

This operation requires permissions for the lex:GetBot action.

Request Syntax

GET /bots/name/versions/versionoralias HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 238)

The name of the bot. The name is case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
versionOrAlias (p. 238)

The version or alias of the bot.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"abortStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"checksum": "string",
"childDirected": boolean,
"clarificationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},

238
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"createdDate": number,
"description": "string",
"failureReason": "string",
"idleSessionTTLInSeconds": number,
"intents": [
{
"intentName": "string",
"intentVersion": "string"
}
],
"lastUpdatedDate": number,
"locale": "string",
"name": "string",
"status": "string",
"version": "string",
"voiceId": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

abortStatement (p. 238)

The message that Amazon Lex returns when the user elects to end the conversation without
completing it. For more information, see PutBot (p. 297).

Type: Statement (p. 365) object


checksum (p. 238)

Checksum of the bot used to identify a specific revision of the bot's $LATEST version.

Type: String
childDirected (p. 238)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify
whether your use of Amazon Lex is related to a website, program, or other application that is
directed or targeted, in whole or in part, to children under age 13 and subject to the Children's
Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field.
By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related
to a website, program, or other application that is directed or targeted, in whole or in part, to
children under age 13 and subject to COPPA. By specifying false in the childDirected field, you
confirm that your use of Amazon Lex is not related to a website, program, or other application that
is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may
not specify a default value for the childDirected field that does not accurately reflect whether
your use of Amazon Lex is related to a website, program, or other application that is directed or
targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in
whole or in part, to children under age 13, you must obtain any required verifiable parental consent
under COPPA. For information regarding the use of Amazon Lex in connection with websites,
programs, or other applications that are directed or targeted, in whole or in part, to children under
age 13, see the Amazon Lex FAQ.

Type: Boolean
clarificationPrompt (p. 238)

The message Amazon Lex uses when it doesn't understand the user's request. For more information,
see PutBot (p. 297).

239
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: Prompt (p. 359) object


createdDate (p. 238)

The date that the bot was created.

Type: Timestamp
description (p. 238)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


failureReason (p. 238)

If status is FAILED, Amazon Lex explains why it failed to build the bot.

Type: String
idleSessionTTLInSeconds (p. 238)

The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. For
more information, see PutBot (p. 297).

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400.


intents (p. 238)

An array of intent objects. For more information, see PutBot (p. 297).

Type: Array of Intent (p. 355) objects


lastUpdatedDate (p. 238)

The date that the bot was updated. When you create a resource, the creation date and last updated
date are the same.

Type: Timestamp
locale (p. 238)

The target locale for the bot.

Type: String

Valid Values: en-US


name (p. 238)

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
status (p. 238)

The status of the bot.

When the status is BUILDING Amazon Lex is building the bot for testing and use.

240
Amazon Lex Developer Guide
Amazon Lex Model Building Service

If the status of the bot is READY_BASIC_TESTING, you can test the bot using the exact utterances
specified in the bot's intents. When the bot is ready for full testing or to run, the status is READY.

If there was a problem with building the bot, the status is FAILED and the failureReason field
explains why the bot did not build.

If the bot was saved but not built, the status is NOT_BUILT.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT


version (p. 238)

The version of the bot. For a new bot, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+
voiceId (p. 238)

The Amazon Polly voice ID that Amazon Lex uses for voice interaction with the user. For more
information, see PutBot (p. 297).

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET

241
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

242
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBotAlias
Service: Amazon Lex Model Building Service

Returns information about an Amazon Lex bot alias. For more information about aliases, see Versioning
and Aliases (p. 97).

This operation requires permissions for the lex:GetBotAlias action.

Request Syntax

GET /bots/botName/aliases/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botName (p. 243)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
name (p. 243)

The name of the bot alias. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"botName": "string",
"botVersion": "string",
"checksum": "string",
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

botName (p. 243)

The name of the bot that the alias points to.

243
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
botVersion (p. 243)

The version of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+
checksum (p. 243)

Checksum of the bot alias.

Type: String
createdDate (p. 243)

The date that the bot alias was created.

Type: Timestamp
description (p. 243)

A description of the bot alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


lastUpdatedDate (p. 243)

The date that the bot alias was updated. When you create a resource, the creation date and the last
updated date are the same.

Type: Timestamp
name (p. 243)

The name of the bot alias.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

244
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

245
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBotAliases
Service: Amazon Lex Model Building Service

Returns a list of aliases for a specified Amazon Lex bot.

This operation requires permissions for the lex:GetBotAliases action.

Request Syntax

GET /bots/botName/aliases/?
maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botName (p. 246)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
maxResults (p. 246)

The maximum number of aliases to return in the response. The default is 50. .

Valid Range: Minimum value of 1. Maximum value of 50.


nameContains (p. 246)

Substring to match in bot alias names. An alias will be returned if any part of its name matches the
substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 246)

A pagination token for fetching the next page of aliases. If the response to this call is truncated,
Amazon Lex returns a pagination token in the response. To fetch the next page of aliases, specify the
pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"BotAliases": [
{
"botName": "string",
"botVersion": "string",
"checksum": "string",

246
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string"
}
],
"nextToken": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

BotAliases (p. 246)

An array of BotAliasMetadata objects, each describing a bot alias.

Type: Array of BotAliasMetadata (p. 342) objects


nextToken (p. 246)

A pagination token for fetching next page of aliases. If the response to this call is truncated, Amazon
Lex returns a pagination token in the response. To fetch the next page of aliases, specify the
pagination token in the next request.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java

247
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for JavaScript


• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

248
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBotChannelAssociation
Service: Amazon Lex Model Building Service

Returns information about the association between an Amazon Lex bot and a messaging platform.

This operation requires permissions for the lex:GetBotChannelAssociation action.

Request Syntax

GET /bots/botName/aliases/aliasName/channels/name HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botAlias (p. 249)

An alias pointing to the specific version of the Amazon Lex bot to which this association is being
made.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
botName (p. 249)

The name of the Amazon Lex bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
name (p. 249)

The name of the association between the bot and the channel. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"botAlias": "string",
"botConfiguration": {
"string" : "string"
},
"botName": "string",
"createdDate": number,
"description": "string",
"failureReason": "string",
"name": "string",
"status": "string",

249
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"type": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

botAlias (p. 249)

An alias pointing to the specific version of the Amazon Lex bot to which this association is being
made.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
botConfiguration (p. 249)

Provides information that the messaging platform needs to communicate with the Amazon Lex bot.

Type: String to string map


botName (p. 249)

The name of the Amazon Lex bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
createdDate (p. 249)

The date that the association between the bot and the channel was created.

Type: Timestamp
description (p. 249)

A description of the association between the bot and the channel.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


failureReason (p. 249)

If status is FAILED, Amazon Lex provides the reason that it failed to create the association.

Type: String
name (p. 249)

The name of the association between the bot and the channel.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

250
Amazon Lex Developer Guide
Amazon Lex Model Building Service

status (p. 249)

The status of the bot channel.


• CREATED - The channel has been created and is ready for use.
• IN_PROGRESS - Channel creation is in progress.
• FAILED - There was an error creating the channel. For information about the reason for the
failure, see the failureReason field.

Type: String

Valid Values: IN_PROGRESS | CREATED | FAILED


type (p. 249)

The type of the messaging platform.

Type: String

Valid Values: Facebook | Slack | Twilio-Sms | Kik

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python

251
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Ruby V2

252
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBotChannelAssociations
Service: Amazon Lex Model Building Service

Returns a list of all of the channels associated with the specified bot.

The GetBotChannelAssociations operation requires permissions for the


lex:GetBotChannelAssociations action.

Request Syntax

GET /bots/botName/aliases/aliasName/channels/?
maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botAlias (p. 253)

An alias pointing to the specific version of the Amazon Lex bot to which this association is being
made.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^(-|^([A-Za-z]_?)+$)$
botName (p. 253)

The name of the Amazon Lex bot in the association.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
maxResults (p. 253)

The maximum number of associations to return in the response. The default is 50.

Valid Range: Minimum value of 1. Maximum value of 50.


nameContains (p. 253)

Substring to match in channel association names. An association will be returned if any part of its
name matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz." To return all
bot channel associations, use a hyphen ("-") as the nameContains parameter.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 253)

A pagination token for fetching the next page of associations. If the response to this call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
associations, specify the pagination token in the next request.

Request Body
The request does not have a request body.

253
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"botChannelAssociations": [
{
"botAlias": "string",
"botConfiguration": {
"string" : "string"
},
"botName": "string",
"createdDate": number,
"description": "string",
"failureReason": "string",
"name": "string",
"status": "string",
"type": "string"
}
],
"nextToken": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

botChannelAssociations (p. 254)

An array of objects, one for each association, that provides information about the Amazon Lex bot
and its association with the channel.

Type: Array of BotChannelAssociation (p. 344) objects


nextToken (p. 254)

A pagination token that fetches the next page of associations. If the response to this call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
associations, specify the pagination token in the next request.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

254
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 429

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

255
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBots
Service: Amazon Lex Model Building Service

Returns bot information as follows:

• If you provide the nameContains field, the response includes information for the $LATEST version of
all bots whose name contains the specified string.
• If you don't specify the nameContains field, the operation returns information about the $LATEST
version of all of your bots.

This operation requires permission for the lex:GetBots action.

Request Syntax

GET /bots/?maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

maxResults (p. 256)

The maximum number of bots to return in the response that the request will return. The default is
10.

Valid Range: Minimum value of 1. Maximum value of 50.


nameContains (p. 256)

Substring to match in bot names. A bot will be returned if any part of its name matches the
substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 256)

A pagination token that fetches the next page of bots. If the response to this call is truncated,
Amazon Lex returns a pagination token in the response. To fetch the next page of bots, specify the
pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"bots": [
{
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string",

256
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"status": "string",
"version": "string"
}
],
"nextToken": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

bots (p. 256)

An array of botMetadata objects, with one entry for each bot.

Type: Array of BotMetadata (p. 346) objects


nextToken (p. 256)

If the response is truncated, it includes a pagination token that you can specify in your next request
to fetch the next page of bots.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go

257
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Java


• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

258
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBotVersions
Service: Amazon Lex Model Building Service

Gets information about all of the versions of a bot.

The GetBotVersions operation returns a BotMetadata object for each version of a bot. For example,
if a bot has three numbered versions, the GetBotVersions operation returns four BotMetadata
objects in the response, one for each numbered version and one for the $LATEST version.

The GetBotVersions operation always returns at least one version, the $LATEST version.

This operation requires permissions for the lex:GetBotVersions action.

Request Syntax

GET /bots/name/versions/?maxResults=maxResults&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

maxResults (p. 259)

The maximum number of bot versions to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


name (p. 259)

The name of the bot for which versions should be returned.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 259)

A pagination token for fetching the next page of bot versions. If the response to this call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
versions, specify the pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"bots": [
{
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string",
"status": "string",
"version": "string"
}

259
Amazon Lex Developer Guide
Amazon Lex Model Building Service

],
"nextToken": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

bots (p. 259)

An array of BotMetadata objects, one for each numbered version of the bot plus one for the
$LATEST version.

Type: Array of BotMetadata (p. 346) objects


nextToken (p. 259)

A pagination token for fetching the next page of bot versions. If the response to this call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
versions, specify the pagination token in the next request.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go

260
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Java


• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

261
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBuiltinIntent
Service: Amazon Lex Model Building Service

Returns information about a built-in intent.

This operation requires permission for the lex:GetBuiltinIntent action.

Request Syntax

GET /builtins/intents/signature HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

signature (p. 262)

The unique identifier for a built-in intent. To find the signature for an intent, see Standard Built-in
Intents in the Alexa Skills Kit.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"signature": "string",
"slots": [
{
"name": "string"
}
],
"supportedLocales": [ "string" ]
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

signature (p. 262)

The unique identifier for a built-in intent.

Type: String
slots (p. 262)

An array of BuiltinIntentSlot objects, one entry for each slot type in the intent.

Type: Array of BuiltinIntentSlot (p. 349) objects


supportedLocales (p. 262)

A list of locales that the intent supports.

262
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: Array of strings

Valid Values: en-US

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

263
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBuiltinIntents
Service: Amazon Lex Model Building Service

Gets a list of built-in intents that meet the specified criteria.

This operation requires permission for the lex:GetBuiltinIntents action.

Request Syntax

GET /builtins/intents/?
locale=locale&maxResults=maxResults&nextToken=nextToken&signatureContains=signatureContains
HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

locale (p. 264)

A list of locales that the intent supports.

Valid Values: en-US


maxResults (p. 264)

The maximum number of intents to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


nextToken (p. 264)

A pagination token that fetches the next page of intents. If this API call is truncated, Amazon Lex
returns a pagination token in the response. To fetch the next page of intents, use the pagination
token in the next request.
signatureContains (p. 264)

Substring to match in built-in intent signatures. An intent will be returned if any part of its signature
matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz." To find the signature
for an intent, see Standard Built-in Intents in the Alexa Skills Kit.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"intents": [
{
"signature": "string",
"supportedLocales": [ "string" ]
}
],
"nextToken": "string"
}

264
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

intents (p. 264)

An array of builtinIntentMetadata objects, one for each intent in the response.

Type: Array of BuiltinIntentMetadata (p. 348) objects


nextToken (p. 264)

A pagination token that fetches the next page of intents. If the response to this API call is truncated,
Amazon Lex returns a pagination token in the response. To fetch the next page of intents, specify
the pagination token in the next request.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

265
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetBuiltinSlotTypes
Service: Amazon Lex Model Building Service

Gets a list of built-in slot types that meet the specified criteria.

For a list of built-in slot types, see Slot Type Reference in the Alexa Skills Kit.

This operation requires permission for the lex:GetBuiltInSlotTypes action.

Request Syntax

GET /builtins/slottypes/?
locale=locale&maxResults=maxResults&nextToken=nextToken&signatureContains=signatureContains
HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

locale (p. 266)

A list of locales that the slot type supports.

Valid Values: en-US


maxResults (p. 266)

The maximum number of slot types to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


nextToken (p. 266)

A pagination token that fetches the next page of slot types. If the response to this API call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of slot
types, specify the pagination token in the next request.
signatureContains (p. 266)

Substring to match in built-in slot type signatures. A slot type will be returned if any part of its
signature matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"nextToken": "string",
"slotTypes": [
{
"signature": "string",
"supportedLocales": [ "string" ]
}
]
}

266
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

nextToken (p. 266)

If the response is truncated, the response includes a pagination token that you can use in your next
request to fetch the next page of slot types.

Type: String
slotTypes (p. 266)

An array of BuiltInSlotTypeMetadata objects, one entry for each slot type returned.

Type: Array of BuiltinSlotTypeMetadata (p. 350) objects

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

267
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetExport
Service: Amazon Lex Model Building Service

Exports the contents of a Amazon Lex resource in a specified format.

Request Syntax

GET /exports/?exportType=exportType&name=name&resourceType=resourceType&version=version
HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

exportType (p. 268)

The format of the exported data.

Valid Values: ALEXA_SKILLS_KIT | LEX


name (p. 268)

The name of the bot to export.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+
resourceType (p. 268)

The type of resource to export.

Valid Values: BOT | INTENT | SLOT_TYPE


version (p. 268)

The version of the bot to export.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"exportStatus": "string",
"exportType": "string",
"failureReason": "string",
"name": "string",
"resourceType": "string",
"url": "string",
"version": "string"
}

268
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

exportStatus (p. 268)

The status of the export.


• IN_PROGRESS - The export is in progress.
• READY - The export is complete.
• FAILED - The export could not be completed.

Type: String

Valid Values: IN_PROGRESS | READY | FAILED


exportType (p. 268)

The format of the exported data.

Type: String

Valid Values: ALEXA_SKILLS_KIT | LEX


failureReason (p. 268)

If status is FAILED, Amazon Lex provides the reason that it failed to export the resource.

Type: String
name (p. 268)

The name of the bot being exported.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+
resourceType (p. 268)

The type of the exported resource.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE


url (p. 268)

An S3 pre-signed URL that provides the location of the exported resource. The exported resource is
a ZIP archive that contains the exported resource in JSON format. The structure of the archive may
change. Your code should not rely on the archive structure.

Type: String
version (p. 268)

The version of the bot being exported.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

269
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Pattern: [0-9]+

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

270
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetImport
Service: Amazon Lex Model Building Service

Gets information about an import job started with the StartImport operation.

Request Syntax

GET /imports/importId HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

importId (p. 271)

The identifier of the import job information to return.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"createdDate": number,
"failureReason": [ "string" ],
"importId": "string",
"importStatus": "string",
"mergeStrategy": "string",
"name": "string",
"resourceType": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

createdDate (p. 271)

A timestamp for the date and time that the import job was created.

Type: Timestamp
failureReason (p. 271)

A string that describes why an import job failed to complete.

Type: Array of strings


importId (p. 271)

The identifier for the specific import job.

Type: String

271
Amazon Lex Developer Guide
Amazon Lex Model Building Service

importStatus (p. 271)

The status of the import job. If the status is FAILED, you can get the reason for the failure from the
failureReason field.

Type: String

Valid Values: IN_PROGRESS | COMPLETE | FAILED


mergeStrategy (p. 271)

The action taken when there was a conflict between an existing resource and a resource in the
import file.

Type: String

Valid Values: OVERWRITE_LATEST | FAIL_ON_CONFLICT


name (p. 271)

The name given to the import job.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+
resourceType (p. 271)

The type of resource imported.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

272
Amazon Lex Developer Guide
Amazon Lex Model Building Service

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

273
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetIntent
Service: Amazon Lex Model Building Service

Returns information about an intent. In addition to the intent name, you must specify the intent version.

This operation requires permissions to perform the lex:GetIntent action.

Request Syntax

GET /intents/name/versions/version HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 274)

The name of the intent. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
version (p. 274)

The version of the intent.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"checksum": "string",
"conclusionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"confirmationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number

274
Amazon Lex Developer Guide
Amazon Lex Model Building Service

}
],
"responseCard": "string"
},
"createdDate": number,
"description": "string",
"dialogCodeHook": {
"messageVersion": "string",
"uri": "string"
},
"followUpPrompt": {
"prompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
},
"fulfillmentActivity": {
"codeHook": {
"messageVersion": "string",
"uri": "string"
},
"type": "string"
},
"lastUpdatedDate": number,
"name": "string",
"parentIntentSignature": "string",
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"sampleUtterances": [ "string" ],
"slots": [
{
"description": "string",
"name": "string",
"priority": number,
"responseCard": "string",
"sampleUtterances": [ "string" ],
"slotConstraint": "string",
"slotType": "string",
"slotTypeVersion": "string",
"valueElicitationPrompt": {
"maxAttempts": number,

275
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
}
],
"version": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

checksum (p. 274)

Checksum of the intent.

Type: String
conclusionStatement (p. 274)

After the Lambda function specified in the fulfillmentActivity element fulfills the intent,
Amazon Lex conveys this statement to the user.

Type: Statement (p. 365) object


confirmationPrompt (p. 274)

If defined in the bot, Amazon Lex uses prompt to confirm the intent before fulfilling the user's
request. For more information, see PutIntent (p. 309).

Type: Prompt (p. 359) object


createdDate (p. 274)

The date that the intent was created.

Type: Timestamp
description (p. 274)

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


dialogCodeHook (p. 274)

If defined in the bot, Amazon Amazon Lex invokes this Lambda function for each user input. For
more information, see PutIntent (p. 309).

Type: CodeHook (p. 351) object


followUpPrompt (p. 274)

If defined in the bot, Amazon Lex uses this prompt to solicit additional user activity after the intent
is fulfilled. For more information, see PutIntent (p. 309).

276
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: FollowUpPrompt (p. 353) object


fulfillmentActivity (p. 274)

Describes how the intent is fulfilled. For more information, see PutIntent (p. 309).

Type: FulfillmentActivity (p. 354) object


lastUpdatedDate (p. 274)

The date that the intent was updated. When you create a resource, the creation date and the last
updated date are the same.

Type: Timestamp
name (p. 274)

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
parentIntentSignature (p. 274)

A unique identifier for a built-in intent.

Type: String
rejectionStatement (p. 274)

If the user answers "no" to the question defined in confirmationPrompt, Amazon Lex responds
with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 365) object


sampleUtterances (p. 274)

An array of sample utterances configured for the intent.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200.


slots (p. 274)

An array of intent slots configured for the intent.

Type: Array of Slot (p. 361) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items.


version (p. 274)

The version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

277
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

278
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetIntents
Service: Amazon Lex Model Building Service

Returns intent information as follows:

• If you specify the nameContains field, returns the $LATEST version of all intents that contain the
specified string.
• If you don't specify the nameContains field, returns information about the $LATEST version of all
intents.

The operation requires permission for the lex:GetIntents action.

Request Syntax

GET /intents/?maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

maxResults (p. 279)

The maximum number of intents to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


nameContains (p. 279)

Substring to match in intent names. An intent will be returned if any part of its name matches the
substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 279)

A pagination token that fetches the next page of intents. If the response to this API call is truncated,
Amazon Lex returns a pagination token in the response. To fetch the next page of intents, specify
the pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"intents": [
{
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string",
"version": "string"

279
Amazon Lex Developer Guide
Amazon Lex Model Building Service

}
],
"nextToken": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

intents (p. 279)

An array of Intent objects. For more information, see PutBot (p. 297).

Type: Array of IntentMetadata (p. 356) objects


nextToken (p. 279)

If the response is truncated, the response includes a pagination token that you can specify in your
next request to fetch the next page of intents.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java

280
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for JavaScript


• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

281
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetIntentVersions
Service: Amazon Lex Model Building Service

Gets information about all of the versions of an intent.

The GetIntentVersions operation returns an IntentMetadata object for each version of an intent.
For example, if an intent has three numbered versions, the GetIntentVersions operation returns four
IntentMetadata objects in the response, one for each numbered version and one for the $LATEST
version.

The GetIntentVersions operation always returns at least one version, the $LATEST version.

This operation requires permissions for the lex:GetIntentVersions action.

Request Syntax

GET /intents/name/versions/?maxResults=maxResults&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

maxResults (p. 282)

The maximum number of intent versions to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


name (p. 282)

The name of the intent for which versions should be returned.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 282)

A pagination token for fetching the next page of intent versions. If the response to this call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
versions, specify the pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"intents": [
{
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string",
"version": "string"
}

282
Amazon Lex Developer Guide
Amazon Lex Model Building Service

],
"nextToken": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

intents (p. 282)

An array of IntentMetadata objects, one for each numbered version of the intent plus one for the
$LATEST version.

Type: Array of IntentMetadata (p. 356) objects


nextToken (p. 282)

A pagination token for fetching the next page of intent versions. If the response to this call is
truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
versions, specify the pagination token in the next request.

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go

283
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Java


• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

284
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetSlotType
Service: Amazon Lex Model Building Service

Returns information about a specific version of a slot type. In addition to specifying the slot type name,
you must specify the slot type version.

This operation requires permissions for the lex:GetSlotType action.

Request Syntax

GET /slottypes/name/versions/version HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

name (p. 285)

The name of the slot type. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
version (p. 285)

The version of the slot type.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"checksum": "string",
"createdDate": number,
"description": "string",
"enumerationValues": [
{
"synonyms": [ "string" ],
"value": "string"
}
],
"lastUpdatedDate": number,
"name": "string",
"valueSelectionStrategy": "string",
"version": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

285
Amazon Lex Developer Guide
Amazon Lex Model Building Service

The following data is returned in JSON format by the service.

checksum (p. 285)

Checksum of the $LATEST version of the slot type.

Type: String
createdDate (p. 285)

The date that the slot type was created.

Type: Timestamp
description (p. 285)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


enumerationValues (p. 285)

A list of EnumerationValue objects that defines the values that the slot type can take.

Type: Array of EnumerationValue (p. 352) objects

Array Members: Minimum number of 1 item. Maximum number of 10000 items.


lastUpdatedDate (p. 285)

The date that the slot type was updated. When you create a resource, the creation date and last
update date are the same.

Type: Timestamp
name (p. 285)

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
valueSelectionStrategy (p. 285)

The strategy that Amazon Lex uses to determine the value of the slot. For more information, see
PutSlotType (p. 319).

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION


version (p. 285)

The version of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

286
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

287
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetSlotTypes
Service: Amazon Lex Model Building Service

Returns slot type information as follows:

• If you specify the nameContains field, returns the $LATEST version of all slot types that contain the
specified string.
• If you don't specify the nameContains field, returns information about the $LATEST version of all
slot types.

The operation requires permission for the lex:GetSlotTypes action.

Request Syntax

GET /slottypes/?maxResults=maxResults&nameContains=nameContains&nextToken=nextToken
HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

maxResults (p. 288)

The maximum number of slot types to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


nameContains (p. 288)

Substring to match in slot type names. A slot type will be returned if any part of its name matches
the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 288)

A pagination token that fetches the next page of slot types. If the response to this API call is
truncated, Amazon Lex returns a pagination token in the response. To fetch next page of slot types,
specify the pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"nextToken": "string",
"slotTypes": [
{
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,

288
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"name": "string",
"version": "string"
}
]
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

nextToken (p. 288)

If the response is truncated, it includes a pagination token that you can specify in your next request
to fetch the next page of slot types.

Type: String
slotTypes (p. 288)

An array of objects, one for each slot type, that provides information such as the name of the slot
type, the version, and a description.

Type: Array of SlotTypeMetadata (p. 363) objects

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go

289
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Java


• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

290
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetSlotTypeVersions
Service: Amazon Lex Model Building Service

Gets information about all versions of a slot type.

The GetSlotTypeVersions operation returns a SlotTypeMetadata object for each version of a slot
type. For example, if a slot type has three numbered versions, the GetSlotTypeVersions operation
returns four SlotTypeMetadata objects in the response, one for each numbered version and one for
the $LATEST version.

The GetSlotTypeVersions operation always returns at least one version, the $LATEST version.

This operation requires permissions for the lex:GetSlotTypeVersions action.

Request Syntax

GET /slottypes/name/versions/?maxResults=maxResults&nextToken=nextToken HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

maxResults (p. 291)

The maximum number of slot type versions to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50.


name (p. 291)

The name of the slot type for which versions should be returned.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
nextToken (p. 291)

A pagination token for fetching the next page of slot type versions. If the response to this call
is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
versions, specify the pagination token in the next request.

Request Body
The request does not have a request body.

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"nextToken": "string",
"slotTypes": [
{
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string",
"version": "string"

291
Amazon Lex Developer Guide
Amazon Lex Model Building Service

}
]
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

nextToken (p. 291)

A pagination token for fetching the next page of slot type versions. If the response to this call
is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of
versions, specify the pagination token in the next request.

Type: String
slotTypes (p. 291)

An array of SlotTypeMetadata objects, one for each numbered version of the slot type plus one
for the $LATEST version.

Type: Array of SlotTypeMetadata (p. 363) objects

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go

292
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Java


• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

293
Amazon Lex Developer Guide
Amazon Lex Model Building Service

GetUtterancesView
Service: Amazon Lex Model Building Service

Use the GetUtterancesView operation to get information about the utterances that your users have
made to your bot. You can use this list to tune the utterances that your bot responds to.

For example, say that you have created a bot to order flowers. After your users have used your bot for
a while, use the GetUtterancesView operation to see the requests that they have made and whether
they have been successful. You might find that the utterance "I want flowers" is not being recognized.
You could add this utterance to the OrderFlowers intent so that your bot recognizes that utterance.

After you publish a new version of a bot, you can get information about the old version and the new so
that you can compare the performance across the two versions.

Utterance statistics are generated once a day. Data is available for the last 15 days. You can request
information for up to 5 versions of your bot in each request. The response contains information about a
maximum of 100 utterances for each version.

If you set childDirected field to true when you created your bot, or if you opted out of participating
in improving Amazon Lex, utterances are not available.

This operation requires permissions for the lex:GetUtterancesView action.

Request Syntax

GET /bots/botname/utterances?
view=aggregation&bot_versions=botVersions&status_type=statusType HTTP/1.1

URI Request Parameters


The request requires the following URI parameters.

botName (p. 294)

The name of the bot for which utterance information should be returned.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
botVersions (p. 294)

An array of bot versions for which utterance information should be returned. The limit is 5 versions
per request.

Array Members: Minimum number of 1 item. Maximum number of 5 items.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+
statusType (p. 294)

To return utterances that were recognized and handled, useDetected. To return utterances that
were not recognized, use Missed.

Valid Values: Detected | Missed

Request Body
The request does not have a request body.

294
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"botName": "string",
"utterances": [
{
"botVersion": "string",
"utterances": [
{
"count": number,
"distinctUsers": number,
"firstUtteredDate": number,
"lastUtteredDate": number,
"utteranceString": "string"
}
]
}
]
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

botName (p. 295)

The name of the bot for which utterance information was returned.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
utterances (p. 295)

An array of UtteranceList (p. 367) objects, each containing a list of UtteranceData (p. 366) objects
describing the utterances that were processed by your bot. The response contains a maximum of 100
UtteranceData objects for each version.

Type: Array of UtteranceList (p. 367) objects

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500

295
Amazon Lex Developer Guide
Amazon Lex Model Building Service

LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

296
Amazon Lex Developer Guide
Amazon Lex Model Building Service

PutBot
Service: Amazon Lex Model Building Service

Creates an Amazon Lex conversational bot or replaces an existing bot. When you create or update a
bot you are only required to specify a name, a locale, and whether the bot is directed toward children
under age 13. You can use this to add intents later, or to remove intents from an existing bot. When you
create a bot with the minimum information, the bot is created or updated but Amazon Lex returns the
response FAILED. You can build the bot after you add one or more intents. For more information about
Amazon Lex bots, see Amazon Lex: How It Works (p. 3).

If you specify the name of an existing bot, the fields in the request replace the existing values in the
$LATEST version of the bot. Amazon Lex removes any fields that you don't provide values for in the
request, except for the idleTTLInSeconds and privacySettings fields, which are set to their default
values. If you don't specify values for required fields, Amazon Lex throws an exception.

This operation requires permissions for the lex:PutBot action. For more information, see
Authentication and Access Control for Amazon Lex (p. 191).

Request Syntax

PUT /bots/name/versions/$LATEST HTTP/1.1


Content-type: application/json

{
"abortStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"checksum": "string",
"childDirected": boolean,
"clarificationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"createVersion": boolean,
"description": "string",
"idleSessionTTLInSeconds": number,
"intents": [
{
"intentName": "string",
"intentVersion": "string"
}
],
"locale": "string",
"processBehavior": "string",
"voiceId": "string"
}

297
Amazon Lex Developer Guide
Amazon Lex Model Building Service

URI Request Parameters


The request requires the following URI parameters.

name (p. 297)

The name of the bot. The name is not case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

abortStatement (p. 297)

When Amazon Lex can't understand the user's input in context, it tries to elicit the information a few
times. After that, Amazon Lex sends the message defined in abortStatement to the user, and then
aborts the conversation. To set the number of retries, use the valueElicitationPrompt field for
the slot type.

For example, in a pizza ordering bot, Amazon Lex might ask a user "What type of crust would you
like?" If the user's response is not one of the expected responses (for example, "thin crust, "deep
dish," etc.), Amazon Lex tries to elicit a correct response a few more times.

For example, in a pizza ordering application, OrderPizza might be one of the intents. This intent
might require the CrustType slot. You specify the valueElicitationPrompt field when you
create the CrustType slot.

Type: Statement (p. 365) object

Required: No
checksum (p. 297)

Identifies a specific revision of the $LATEST version.

When you create a new bot, leave the checksum field blank. If you specify a checksum you get a
BadRequestException exception.

When you want to update a bot, set the checksum field to the checksum of the most recent revision
of the $LATEST version. If you don't specify the checksum field, or if the checksum does not
match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No
childDirected (p. 297)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify
whether your use of Amazon Lex is related to a website, program, or other application that is
directed or targeted, in whole or in part, to children under age 13 and subject to the Children's
Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field.
By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related
to a website, program, or other application that is directed or targeted, in whole or in part, to
children under age 13 and subject to COPPA. By specifying false in the childDirected field, you
confirm that your use of Amazon Lex is not related to a website, program, or other application that
is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may

298
Amazon Lex Developer Guide
Amazon Lex Model Building Service

not specify a default value for the childDirected field that does not accurately reflect whether
your use of Amazon Lex is related to a website, program, or other application that is directed or
targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in
whole or in part, to children under age 13, you must obtain any required verifiable parental consent
under COPPA. For information regarding the use of Amazon Lex in connection with websites,
programs, or other applications that are directed or targeted, in whole or in part, to children under
age 13, see the Amazon Lex FAQ.

Type: Boolean

Required: Yes
clarificationPrompt (p. 297)

When Amazon Lex doesn't understand the user's intent, it uses this message to get clarification. To
specify how many times Amazon Lex should repeate the clarification prompt, use the maxAttempts
field. If Amazon Lex still doesn't understand, it sends the message in the abortStatement field.

When you create a clarification prompt, make sure that it suggests the correct response from the
user. for example, for a bot that orders pizza and drinks, you might create this clarification prompt:
"What would you like to do? You can say 'Order a pizza' or 'Order a drink.'"

Type: Prompt (p. 359) object

Required: No
createVersion (p. 297)

When set to true a new numbered version of the bot is created. This is the same as calling the
CreateBotVersion operation. If you do not specify createVersion, the default is false.

Type: Boolean

Required: No
description (p. 297)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
idleSessionTTLInSeconds (p. 297)

The maximum time in seconds that Amazon Lex retains the data gathered in a conversation.

A user interaction session remains active for the amount of time specified. If no conversation occurs
during this time, the session expires and Amazon Lex deletes any data provided before the timeout.

For example, suppose that a user chooses the OrderPizza intent, but gets sidetracked halfway
through placing an order. If the user doesn't complete the order within the specified time, Amazon
Lex discards the slot information that it gathered, and the user must start over.

If you don't include the idleSessionTTLInSeconds element in a PutBot operation request,


Amazon Lex uses the default value. This is also true if the request replaces an existing bot.

The default is 300 seconds (5 minutes).

Type: Integer

299
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Valid Range: Minimum value of 60. Maximum value of 86400.

Required: No
intents (p. 297)

An array of Intent objects. Each intent represents a command that a user can express. For example,
a pizza ordering bot might support an OrderPizza intent. For more information, see Amazon Lex:
How It Works (p. 3).

Type: Array of Intent (p. 355) objects

Required: No
locale (p. 297)

Specifies the target locale for the bot. Any intent used in the bot must be compatible with the locale
of the bot.

The default is en-US.

Type: String

Valid Values: en-US

Required: Yes
processBehavior (p. 297)

If you set the processBehavior element to BUILD, Amazon Lex builds the bot so that it can be
run. If you set the element to SAVE Amazon Lex saves the bot, but doesn't build it.

If you don't specify this value, the default value is BUILD.

Type: String

Valid Values: SAVE | BUILD

Required: No
voiceId (p. 297)

The Amazon Polly voice ID that you want Amazon Lex to use for voice interactions with the user. The
locale configured for the voice must match the locale of the bot. For more information, see Voices in
Amazon Polly in the Amazon Polly Developer Guide.

Type: String

Required: No

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"abortStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}

300
Amazon Lex Developer Guide
Amazon Lex Model Building Service

],
"responseCard": "string"
},
"checksum": "string",
"childDirected": boolean,
"clarificationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"createdDate": number,
"createVersion": boolean,
"description": "string",
"failureReason": "string",
"idleSessionTTLInSeconds": number,
"intents": [
{
"intentName": "string",
"intentVersion": "string"
}
],
"lastUpdatedDate": number,
"locale": "string",
"name": "string",
"status": "string",
"version": "string",
"voiceId": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

abortStatement (p. 300)

The message that Amazon Lex uses to abort a conversation. For more information, see
PutBot (p. 297).

Type: Statement (p. 365) object


checksum (p. 300)

Checksum of the bot that you created.

Type: String
childDirected (p. 300)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify
whether your use of Amazon Lex is related to a website, program, or other application that is
directed or targeted, in whole or in part, to children under age 13 and subject to the Children's
Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field.
By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related
to a website, program, or other application that is directed or targeted, in whole or in part, to
children under age 13 and subject to COPPA. By specifying false in the childDirected field, you
confirm that your use of Amazon Lex is not related to a website, program, or other application that

301
Amazon Lex Developer Guide
Amazon Lex Model Building Service

is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may
not specify a default value for the childDirected field that does not accurately reflect whether
your use of Amazon Lex is related to a website, program, or other application that is directed or
targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in
whole or in part, to children under age 13, you must obtain any required verifiable parental consent
under COPPA. For information regarding the use of Amazon Lex in connection with websites,
programs, or other applications that are directed or targeted, in whole or in part, to children under
age 13, see the Amazon Lex FAQ.

Type: Boolean
clarificationPrompt (p. 300)

The prompts that Amazon Lex uses when it doesn't understand the user's intent. For more
information, see PutBot (p. 297).

Type: Prompt (p. 359) object


createdDate (p. 300)

The date that the bot was created.

Type: Timestamp
createVersion (p. 300)

True if a new version of the bot was created. If the createVersion field was not specified in the
request, the createVersion field is set to false in the response.

Type: Boolean
description (p. 300)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


failureReason (p. 300)

If status is FAILED, Amazon Lex provides the reason that it failed to build the bot.

Type: String
idleSessionTTLInSeconds (p. 300)

The maximum length of time that Amazon Lex retains the data gathered in a conversation. For more
information, see PutBot (p. 297).

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400.


intents (p. 300)

An array of Intent objects. For more information, see PutBot (p. 297).

Type: Array of Intent (p. 355) objects


lastUpdatedDate (p. 300)

The date that the bot was updated. When you create a resource, the creation date and last updated
date are the same.

302
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: Timestamp
locale (p. 300)

The target locale for the bot.

Type: String

Valid Values: en-US


name (p. 300)

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
status (p. 300)

When you send a request to create a bot with processBehavior set to BUILD, Amazon Lex sets
the status response element to BUILDING.

In the READY_BASIC_TESTING state you can test the bot with user inputs that exactly match the
utterances configured for the bot's intents and values in the slot types.

If Amazon Lex can't build the bot, Amazon Lex sets status to FAILED. Amazon Lex returns the
reason for the failure in the failureReason response element.

When you set processBehavior to SAVE, Amazon Lex sets the status code to NOT BUILT.

When the bot is in the READY state you can test and publish the bot.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT


version (p. 300)

The version of the bot. For a new bot, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+
voiceId (p. 300)

The Amazon Polly voice ID that Amazon Lex uses for voice interaction with the user. For more
information, see PutBot (p. 297).

Type: String

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400

303
Amazon Lex Developer Guide
Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

304
Amazon Lex Developer Guide
Amazon Lex Model Building Service

PutBotAlias
Service: Amazon Lex Model Building Service

Creates an alias for the specified version of the bot or replaces an alias for the specified bot. To change
the version of the bot that the alias points to, replace the alias. For more information about aliases, see
Versioning and Aliases (p. 97).

This operation requires permissions for the lex:PutBotAlias action.

Request Syntax

PUT /bots/botName/aliases/name HTTP/1.1


Content-type: application/json

{
"botVersion": "string",
"checksum": "string",
"description": "string"
}

URI Request Parameters


The request requires the following URI parameters.

botName (p. 305)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
name (p. 305)

The name of the alias. The name is not case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

botVersion (p. 305)

The version of the bot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes
checksum (p. 305)

Identifies a specific revision of the $LATEST version.

305
Amazon Lex Developer Guide
Amazon Lex Model Building Service

When you create a new bot alias, leave the checksum field blank. If you specify a checksum you get
a BadRequestException exception.

When you want to update a bot alias, set the checksum field to the checksum of the most recent
revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does
not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No
description (p. 305)

A description of the alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"botName": "string",
"botVersion": "string",
"checksum": "string",
"createdDate": number,
"description": "string",
"lastUpdatedDate": number,
"name": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

botName (p. 306)

The name of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$
botVersion (p. 306)

The version of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

306
Amazon Lex Developer Guide
Amazon Lex Model Building Service

checksum (p. 306)

The checksum for the current version of the alias.

Type: String
createdDate (p. 306)

The date that the bot alias was created.

Type: Timestamp
description (p. 306)

A description of the alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


lastUpdatedDate (p. 306)

The date that the bot alias was updated. When you create a resource, the creation date and the last
updated date are the same.

Type: Timestamp
name (p. 306)

The name of the alias.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429


PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

307
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

308
Amazon Lex Developer Guide
Amazon Lex Model Building Service

PutIntent
Service: Amazon Lex Model Building Service

Creates an intent or replaces an existing intent.

To define the interaction between the user and your bot, you use one or more intents. For a pizza
ordering bot, for example, you would create an OrderPizza intent.

To create an intent or replace an existing intent, you must provide the following:

• Intent name. For example, OrderPizza.


• Sample utterances. For example, "Can I order a pizza, please." and "I want to order a pizza."
• Information to be gathered. You specify slot types for the information that your bot will request from
the user. You can specify standard slot types, such as a date or a time, or custom slot types such as the
size and crust of a pizza.
• How the intent will be fulfilled. You can provide a Lambda function or configure the intent to return
the intent information to the client application. If you use a Lambda function, when all of the intent
information is available, Amazon Lex invokes your Lambda function. If you configure your intent to
return the intent information to the client application.

You can specify other optional information in the request, such as:

• A confirmation prompt to ask the user to confirm an intent. For example, "Shall I order your pizza?"
• A conclusion statement to send to the user after the intent has been fulfilled. For example, "I placed
your pizza order."
• A follow-up prompt that asks the user for additional activity. For example, asking "Do you want to
order a drink with your pizza?"

If you specify an existing intent name to update the intent, Amazon Lex replaces the values in the
$LATEST version of the intent with the values in the request. Amazon Lex removes fields that you don't
provide in the request. If you don't specify the required fields, Amazon Lex throws an exception. When
you update the $LATEST version of an intent, the status field of any bot that uses the $LATEST version
of the intent is set to NOT_BUILT.

For more information, see Amazon Lex: How It Works (p. 3).

This operation requires permissions for the lex:PutIntent action.

Request Syntax

PUT /intents/name/versions/$LATEST HTTP/1.1


Content-type: application/json

{
"checksum": "string",
"conclusionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"confirmationPrompt": {
"maxAttempts": number,

309
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"createVersion": boolean,
"description": "string",
"dialogCodeHook": {
"messageVersion": "string",
"uri": "string"
},
"followUpPrompt": {
"prompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
},
"fulfillmentActivity": {
"codeHook": {
"messageVersion": "string",
"uri": "string"
},
"type": "string"
},
"parentIntentSignature": "string",
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"sampleUtterances": [ "string" ],
"slots": [
{
"description": "string",
"name": "string",
"priority": number,
"responseCard": "string",
"sampleUtterances": [ "string" ],
"slotConstraint": "string",
"slotType": "string",

310
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"slotTypeVersion": "string",
"valueElicitationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
}
]
}

URI Request Parameters


The request requires the following URI parameters.

name (p. 309)

The name of the intent. The name is not case sensitive.

The name can't match a built-in intent name, or a built-in intent name with "AMAZON." removed. For
example, because there is a built-in intent called AMAZON.HelpIntent, you can't create a custom
intent called HelpIntent.

For a list of built-in intents, see Standard Built-in Intents in the Alexa Skills Kit.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

checksum (p. 309)

Identifies a specific revision of the $LATEST version.

When you create a new intent, leave the checksum field blank. If you specify a checksum you get a
BadRequestException exception.

When you want to update a intent, set the checksum field to the checksum of the most recent
revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does
not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No
conclusionStatement (p. 309)

The statement that you want Amazon Lex to convey to the user after the intent is successfully
fulfilled by the Lambda function.

This element is relevant only if you provide a Lambda function in the fulfillmentActivity. If
you return the intent to the client application, you can't specify this element.

311
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Note
The followUpPrompt and conclusionStatement are mutually exclusive. You can specify
only one.

Type: Statement (p. 365) object

Required: No
confirmationPrompt (p. 309)

Prompts the user to confirm the intent. This question should have a yes or no answer.

Amazon Lex uses this prompt to ensure that the user acknowledges that the intent is ready for
fulfillment. For example, with the OrderPizza intent, you might want to confirm that the order is
correct before placing it. For other intents, such as intents that simply respond to user questions, you
might not need to ask the user for confirmation before providing the information.
Note
You you must provide both the rejectionStatement and the confirmationPrompt, or
neither.

Type: Prompt (p. 359) object

Required: No
createVersion (p. 309)

When set to true a new numbered version of the intent is created. This is the same as calling the
CreateIntentVersion operation. If you do not specify createVersion, the default is false.

Type: Boolean

Required: No
description (p. 309)

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
dialogCodeHook (p. 309)

Specifies a Lambda function to invoke for each user input. You can invoke this Lambda function to
personalize user interaction.

For example, suppose your bot determines that the user is John. Your Lambda function might
retrieve John's information from a backend database and prepopulate some of the values. For
example, if you find that John is gluten intolerant, you might set the corresponding intent slot,
GlutenIntolerant, to true. You might find John's phone number and set the corresponding
session attribute.

Type: CodeHook (p. 351) object

Required: No
followUpPrompt (p. 309)

Amazon Lex uses this prompt to solicit additional activity after fulfilling an intent. For example, after
the OrderPizza intent is fulfilled, you might prompt the user to order a drink.

The action that Amazon Lex takes depends on the user's response, as follows:

312
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• If the user says "Yes" it responds with the clarification prompt that is configured for the bot.
• if the user says "Yes" and continues with an utterance that triggers an intent it starts a
conversation for the intent.
• If the user says "No" it responds with the rejection statement configured for the the follow-up
prompt.
• If it doesn't recognize the utterance it repeats the follow-up prompt again.

The followUpPrompt field and the conclusionStatement field are mutually exclusive. You can
specify only one.

Type: FollowUpPrompt (p. 353) object

Required: No
fulfillmentActivity (p. 309)

Required. Describes how the intent is fulfilled. For example, after a user provides all of the
information for a pizza order, fulfillmentActivity defines how the bot places an order with a
local pizza store.

You might configure Amazon Lex to return all of the intent information to the client application, or
direct it to invoke a Lambda function that can process the intent (for example, place an order with a
pizzeria).

Type: FulfillmentActivity (p. 354) object

Required: No
parentIntentSignature (p. 309)

A unique identifier for the built-in intent to base this intent on. To find the signature for an intent,
see Standard Built-in Intents in the Alexa Skills Kit.

Type: String

Required: No
rejectionStatement (p. 309)

When the user answers "no" to the question defined in confirmationPrompt, Amazon Lex
responds with this statement to acknowledge that the intent was canceled.
Note
You must provide both the rejectionStatement and the confirmationPrompt, or
neither.

Type: Statement (p. 365) object

Required: No
sampleUtterances (p. 309)

An array of utterances (strings) that a user might say to signal the intent. For example, "I want
{PizzaSize} pizza", "Order {Quantity} {PizzaSize} pizzas".

In each utterance, a slot name is enclosed in curly braces.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200.

Required: No

313
Amazon Lex Developer Guide
Amazon Lex Model Building Service

slots (p. 309)

An array of intent slots. At runtime, Amazon Lex elicits required slot values from the user using
prompts defined in the slots. For more information, see Amazon Lex: How It Works (p. 3).

Type: Array of Slot (p. 361) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items.

Required: No

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"checksum": "string",
"conclusionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"confirmationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"createdDate": number,
"createVersion": boolean,
"description": "string",
"dialogCodeHook": {
"messageVersion": "string",
"uri": "string"
},
"followUpPrompt": {
"prompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",

314
Amazon Lex Developer Guide
Amazon Lex Model Building Service

"groupNumber": number
}
],
"responseCard": "string"
}
},
"fulfillmentActivity": {
"codeHook": {
"messageVersion": "string",
"uri": "string"
},
"type": "string"
},
"lastUpdatedDate": number,
"name": "string",
"parentIntentSignature": "string",
"rejectionStatement": {
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
},
"sampleUtterances": [ "string" ],
"slots": [
{
"description": "string",
"name": "string",
"priority": number,
"responseCard": "string",
"sampleUtterances": [ "string" ],
"slotConstraint": "string",
"slotType": "string",
"slotTypeVersion": "string",
"valueElicitationPrompt": {
"maxAttempts": number,
"messages": [
{
"content": "string",
"contentType": "string",
"groupNumber": number
}
],
"responseCard": "string"
}
}
],
"version": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

checksum (p. 314)

Checksum of the $LATESTversion of the intent created or updated.

Type: String

315
Amazon Lex Developer Guide
Amazon Lex Model Building Service

conclusionStatement (p. 314)

After the Lambda function specified in thefulfillmentActivityintent fulfills the intent, Amazon
Lex conveys this statement to the user.

Type: Statement (p. 365) object


confirmationPrompt (p. 314)

If defined in the intent, Amazon Lex prompts the user to confirm the intent before fulfilling it.

Type: Prompt (p. 359) object


createdDate (p. 314)

The date that the intent was created.

Type: Timestamp
createVersion (p. 314)

True if a new version of the intent was created. If the createVersion field was not specified in the
request, the createVersion field is set to false in the response.

Type: Boolean
description (p. 314)

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


dialogCodeHook (p. 314)

If defined in the intent, Amazon Lex invokes this Lambda function for each user input.

Type: CodeHook (p. 351) object


followUpPrompt (p. 314)

If defined in the intent, Amazon Lex uses this prompt to solicit additional user activity after the
intent is fulfilled.

Type: FollowUpPrompt (p. 353) object


fulfillmentActivity (p. 314)

If defined in the intent, Amazon Lex invokes this Lambda function to fulfill the intent after the user
provides all of the information required by the intent.

Type: FulfillmentActivity (p. 354) object


lastUpdatedDate (p. 314)

The date that the intent was updated. When you create a resource, the creation date and last update
dates are the same.

Type: Timestamp
name (p. 314)

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

316
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Pattern: ^([A-Za-z]_?)+$
parentIntentSignature (p. 314)

A unique identifier for the built-in intent that this intent is based on.

Type: String
rejectionStatement (p. 314)

If the user answers "no" to the question defined in confirmationPrompt Amazon Lex responds
with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 365) object


sampleUtterances (p. 314)

An array of sample utterances that are configured for the intent.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200.


slots (p. 314)

An array of intent slots that are configured for the intent.

Type: Array of Slot (p. 361) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items.


version (p. 314)

The version of the intent. For a new intent, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

317
Amazon Lex Developer Guide
Amazon Lex Model Building Service

HTTP Status Code: 429


PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

318
Amazon Lex Developer Guide
Amazon Lex Model Building Service

PutSlotType
Service: Amazon Lex Model Building Service

Creates a custom slot type or replaces an existing custom slot type.

To create a custom slot type, specify a name for the slot type and a set of enumeration values, which
are the values that a slot of this type can assume. For more information, see Amazon Lex: How It
Works (p. 3).

If you specify the name of an existing slot type, the fields in the request replace the existing values in the
$LATEST version of the slot type. Amazon Lex removes the fields that you don't provide in the request.
If you don't specify required fields, Amazon Lex throws an exception. When you update the $LATEST
version of a slot type, if a bot uses the $LATEST version of an intent that contains the slot type, the bot's
status field is set to NOT_BUILT.

This operation requires permissions for the lex:PutSlotType action.

Request Syntax

PUT /slottypes/name/versions/$LATEST HTTP/1.1


Content-type: application/json

{
"checksum": "string",
"createVersion": boolean,
"description": "string",
"enumerationValues": [
{
"synonyms": [ "string" ],
"value": "string"
}
],
"valueSelectionStrategy": "string"
}

URI Request Parameters


The request requires the following URI parameters.

name (p. 319)

The name of the slot type. The name is not case sensitive.

The name can't match a built-in slot type name, or a built-in slot type name with "AMAZON."
removed. For example, because there is a built-in slot type called AMAZON.DATE, you can't create a
custom slot type called DATE.

For a list of built-in slot types, see Slot Type Reference in the Alexa Skills Kit.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Request Body
The request accepts the following data in JSON format.

checksum (p. 319)

Identifies a specific revision of the $LATEST version.

319
Amazon Lex Developer Guide
Amazon Lex Model Building Service

When you create a new slot type, leave the checksum field blank. If you specify a checksum you get
a BadRequestException exception.

When you want to update a slot type, set the checksum field to the checksum of the most recent
revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does
not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No
createVersion (p. 319)

When set to true a new numbered version of the slot type is created. This is the same as calling the
CreateSlotTypeVersion operation. If you do not specify createVersion, the default is false.

Type: Boolean

Required: No
description (p. 319)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
enumerationValues (p. 319)

A list of EnumerationValue objects that defines the values that the slot type can take. Each value
can have a list of synonyms, which are additional values that help train the machine learning model
about the values that it resolves for a slot.

When Amazon Lex resolves a slot value, it generates a resolution list that contains up to five possible
values for the slot. If you are using a Lambda function, this resolution list is passed to the function. If
you are not using a Lambda function you can choose to return the value that the user entered or the
first value in the resolution list as the slot value. The valueSelectionStrategy field indicates the
option to use.

Type: Array of EnumerationValue (p. 352) objects

Array Members: Minimum number of 1 item. Maximum number of 10000 items.

Required: No
valueSelectionStrategy (p. 319)

Determines the slot resolution strategy that Amazon Lex uses to return slot type values. The field
can be set to one of the following values:
• ORIGINAL_VALUE - Returns the value entered by the user, if the user value is similar to the slot
value.
• TOP_RESOLUTION - If there is a resolution list for the slot, return the first value in the resolution
list as the slot type value. If there is no resolution list, null is returned.

If you don't specify the valueSelectionStrategy, the default is ORIGINAL_VALUE.

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION

320
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Required: No

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"checksum": "string",
"createdDate": number,
"createVersion": boolean,
"description": "string",
"enumerationValues": [
{
"synonyms": [ "string" ],
"value": "string"
}
],
"lastUpdatedDate": number,
"name": "string",
"valueSelectionStrategy": "string",
"version": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

checksum (p. 321)

Checksum of the $LATEST version of the slot type.

Type: String
createdDate (p. 321)

The date that the slot type was created.

Type: Timestamp
createVersion (p. 321)

True if a new version of the slot type was created. If the createVersion field was not specified in
the request, the createVersion field is set to false in the response.

Type: Boolean
description (p. 321)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.


enumerationValues (p. 321)

A list of EnumerationValue objects that defines the values that the slot type can take.

Type: Array of EnumerationValue (p. 352) objects

321
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Array Members: Minimum number of 1 item. Maximum number of 10000 items.


lastUpdatedDate (p. 321)

The date that the slot type was updated. When you create a slot type, the creation date and last
update date are the same.

Type: Timestamp
name (p. 321)

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$
valueSelectionStrategy (p. 321)

The slot resolution strategy that Amazon Lex uses to determine the value of the slot. For more
information, see PutSlotType (p. 319).

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION


version (p. 321)

The version of the slot type. For a new slot type, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

322
Amazon Lex Developer Guide
Amazon Lex Model Building Service

PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the
request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

323
Amazon Lex Developer Guide
Amazon Lex Model Building Service

StartImport
Service: Amazon Lex Model Building Service

Starts a job to import a resource to Amazon Lex.

Request Syntax

POST /imports/ HTTP/1.1


Content-type: application/json

{
"mergeStrategy": "string",
"payload": blob,
"resourceType": "string"
}

URI Request Parameters


The request does not use any URI parameters.

Request Body
The request accepts the following data in JSON format.

mergeStrategy (p. 324)

Specifies the action that the StartImport operation should take when there is an existing resource
with the same name.
• FAIL_ON_CONFLICT - The import operation is stopped on the first conflict between a resource in
the import file and an existing resource. The name of the resource causing the conflict is in the
failureReason field of the response to the GetImport operation.

OVERWRITE_LATEST - The import operation proceeds even if there is a conflict with an existing
resource. The $LASTEST version of the existing resource is overwritten with the data from the
import file.

Type: String

Valid Values: OVERWRITE_LATEST | FAIL_ON_CONFLICT

Required: Yes
payload (p. 324)

A zip archive in binary format. The archive should contain one file, a JSON file containing the
resource to import. The resource should match the type specified in the resourceType field.

Type: Base64-encoded binary data object

Required: Yes
resourceType (p. 324)

Specifies the type of resource to export. Each resource also exports any resources that it depends on.
• A bot exports dependent intents.
• An intent exports dependent slot types.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE

324
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Required: Yes

Response Syntax

HTTP/1.1 201
Content-type: application/json

{
"createdDate": number,
"importId": "string",
"importStatus": "string",
"mergeStrategy": "string",
"name": "string",
"resourceType": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service.

createdDate (p. 325)

A timestamp for the date and time that the import job was requested.

Type: Timestamp
importId (p. 325)

The identifier for the specific import job.

Type: String
importStatus (p. 325)

The status of the import job. If the status is FAILED, you can get the reason for the failure using the
GetImport operation.

Type: String

Valid Values: IN_PROGRESS | COMPLETE | FAILED


mergeStrategy (p. 325)

The action to take when there is a merge conflict.

Type: String

Valid Values: OVERWRITE_LATEST | FAIL_ON_CONFLICT


name (p. 325)

The name given to the import job.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+
resourceType (p. 325)

The type of resource to import.

325
Amazon Lex Developer Guide
Amazon Lex Runtime Service

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE

Errors
BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check
the field values, and try again.

HTTP Status Code: 400


InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500


LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

Amazon Lex Runtime Service


The following actions are supported by Amazon Lex Runtime Service:

• PostContent (p. 327)


• PostText (p. 335)

326
Amazon Lex Developer Guide
Amazon Lex Runtime Service

PostContent
Service: Amazon Lex Runtime Service

Sends user input (text or speech) to Amazon Lex. Clients use this API to send text and audio requests to
Amazon Lex at runtime. Amazon Lex interprets the user input using the machine learning model that it
built for the bot.

The PostContent operation supports audio input at 8kHz and 16kHz. You can use 8kHz audio to
achieve higher speech recognition accuracy in telephone audio applications.

In response, Amazon Lex returns the next message to convey to the user. Consider the following example
messages:

• For a user input "I would like a pizza," Amazon Lex might return a response with a message eliciting
slot data (for example, PizzaSize): "What size pizza would you like?".
• After the user provides all of the pizza order information, Amazon Lex might return a response with a
message to get user confirmation: "Order the pizza?".
• After the user replies "Yes" to the confirmation prompt, Amazon Lex might return a conclusion
statement: "Thank you, your cheese pizza has been ordered.".

Not all Amazon Lex messages require a response from the user. For example, conclusion statements do
not require a response. Some messages require only a yes or no response. In addition to the message,
Amazon Lex provides additional context about the message in the response that you can use to enhance
client behavior, such as displaying the appropriate client user interface. Consider the following examples:

• If the message is to elicit slot data, Amazon Lex returns the following context information:
• x-amz-lex-dialog-state header set to ElicitSlot
• x-amz-lex-intent-name header set to the intent name in the current context
• x-amz-lex-slot-to-elicit header set to the slot name for which the message is eliciting
information
• x-amz-lex-slots header set to a map of slots configured for the intent with their current values
• If the message is a confirmation prompt, the x-amz-lex-dialog-state header is set to
Confirmation and the x-amz-lex-slot-to-elicit header is omitted.
• If the message is a clarification prompt configured for the intent, indicating that the user intent is not
understood, the x-amz-dialog-state header is set to ElicitIntent and the x-amz-slot-to-
elicit header is omitted.

In addition, Amazon Lex also returns your application-specific sessionAttributes. For more
information, see Managing Conversation Context.

Request Syntax

POST /bot/botName/alias/botAlias/user/userId/content HTTP/1.1


x-amz-lex-session-attributes: sessionAttributes
x-amz-lex-request-attributes: requestAttributes
Content-Type: contentType
Accept: accept

inputStream

URI Request Parameters


The request requires the following URI parameters.

327
Amazon Lex Developer Guide
Amazon Lex Runtime Service

accept (p. 327)

You pass this value as the Accept HTTP header.

The message Amazon Lex returns in the response can be either text or speech based on the Accept
HTTP header value in the request.
• If the value is text/plain; charset=utf-8, Amazon Lex returns text in the response.
• If the value begins with audio/, Amazon Lex returns speech in the response. Amazon Lex uses
Amazon Polly to generate the speech (using the configuration you specified in the Accept
header). For example, if you specify audio/mpeg as the value, Amazon Lex returns speech in the
MPEG format.

The following are the accepted values:


• audio/mpeg
• audio/ogg
• audio/pcm
• text/plain; charset=utf-8
• audio/* (defaults to mpeg)
botAlias (p. 327)

Alias of the Amazon Lex bot.


botName (p. 327)

Name of the Amazon Lex bot.


contentType (p. 327)

You pass this value as the Content-Type HTTP header.

Indicates the audio format or text. The header value must start with one of the following prefixes:
• PCM format, audio data must be in little-endian byte order.
• audio/l16; rate=16000; channels=1
• audio/x-l16; sample-rate=16000; channel-count=1
• audio/lpcm; sample-rate=8000; sample-size-bits=16; channel-count=1; is-big-endian=false
• Opus format
• audio/x-cbr-opus-with-preamble; preamble-size=0; bit-rate=256000; frame-size-milliseconds=4
• Text format
• text/plain; charset=utf-8
requestAttributes (p. 327)

You pass this value as the x-amz-lex-request-attributes HTTP header.

Request-specific information passed between Amazon Lex and a client application. The value must
be a JSON serialized and base64 encoded map with string keys and values. The total size of the
requestAttributes and sessionAttributes headers is limited to 12 KB.

The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes
with the prefix x-amz-lex:.

For more information, see Setting Request Attributes.


sessionAttributes (p. 327)

You pass this value as the x-amz-lex-session-attributes HTTP header.

328
Amazon Lex Developer Guide
Amazon Lex Runtime Service

Application-specific information passed between Amazon Lex and a client application. The value
must be a JSON serialized and base64 encoded map with string keys and values. The total size of the
sessionAttributes and requestAttributes headers is limited to 12 KB.

For more information, see Setting Session Attributes.


userId (p. 327)

The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your
bot. At runtime, each request must contain the userID field.

To decide the user ID to use for your application, consider the following factors.
• The userID field must not contain any personally identifiable information of the user, for
example, name, personal identification numbers, or other end user personal information.
• If you want a user to start a conversation on one device and continue on another device, use a
user-specific identifier.
• If you want the same user to be able to have two independent conversations on two different
devices, choose a device-specific identifier.
• A user can't have two independent conversations with two different versions of the same bot. For
example, a user can't have a conversation with the PROD and BETA versions of the same bot. If
you anticipate that a user will need to have conversation with two different versions, for example,
while testing, include the bot alias in the user ID to separate the two conversations.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Request Body
The request accepts the following binary data.

inputStream (p. 327)

User input in PCM or Opus audio format or text format as described in the Content-Type HTTP
header.

You can stream audio data to Amazon Lex or you can create a local buffer that captures all of the
audio data before sending. In general, you get better performance if you stream audio data rather
than buffering the data locally.

Response Syntax

HTTP/1.1 200
Content-Type: contentType
x-amz-lex-intent-name: intentName
x-amz-lex-slots: slots
x-amz-lex-session-attributes: sessionAttributes
x-amz-lex-message: message
x-amz-lex-message-format: messageFormat
x-amz-lex-dialog-state: dialogState
x-amz-lex-slot-to-elicit: slotToElicit
x-amz-lex-input-transcript: inputTranscript

audioStream

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

329
Amazon Lex Developer Guide
Amazon Lex Runtime Service

The response returns the following HTTP headers.

contentType (p. 329)

Content type as specified in the Accept HTTP header in the request.


dialogState (p. 329)

Identifies the current state of the user interaction. Amazon Lex returns one of the following values
as dialogState. The client can optionally use this information to customize the user interface.
• ElicitIntent - Amazon Lex wants to elicit the user's intent. Consider the following examples:

For example, a user might utter an intent ("I want to order a pizza"). If Amazon Lex cannot infer
the user intent from this utterance, it will return this dialog state.
• ConfirmIntent - Amazon Lex is expecting a "yes" or "no" response.

For example, Amazon Lex wants user confirmation before fulfilling an intent. Instead of a simple
"yes" or "no" response, a user might respond with additional information. For example, "yes,
but make it a thick crust pizza" or "no, I want to order a drink." Amazon Lex can process such
additional information (in these examples, update the crust type slot or change the intent from
OrderPizza to OrderDrink).
• ElicitSlot - Amazon Lex is expecting the value of a slot for the current intent.

For example, suppose that in the response Amazon Lex sends this message: "What size pizza
would you like?". A user might reply with the slot value (e.g., "medium"). The user might also
provide additional information in the response (e.g., "medium thick crust pizza"). Amazon Lex can
process such additional information appropriately.
• Fulfilled - Conveys that the Lambda function has successfully fulfilled the intent.
• ReadyForFulfillment - Conveys that the client has to fulfill the request.
• Failed - Conveys that the conversation with the user failed.

This can happen for various reasons, including that the user does not provide an appropriate
response to prompts from the service (you can configure how many times Amazon Lex can prompt
a user for specific information), or if the Lambda function fails to fulfill the intent.

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Fulfilled |


ReadyForFulfillment | Failed
inputTranscript (p. 329)

The text used to process the request.

If the input was an audio stream, the inputTranscript field contains the text extracted from the
audio stream. This is the text that is actually processed to recognize intents and slot values. You can
use this information to determine if Amazon Lex is correctly processing the audio that you send.
intentName (p. 329)

Current user intent that Amazon Lex is aware of.


message (p. 329)

The message to convey to the user. The message can come from the bot's configuration or from a
Lambda function.

If the intent is not configured with a Lambda function, or if the Lambda function returned
Delegate as the dialogAction.type its response, Amazon Lex decides on the next course
of action and selects an appropriate message from the bot's configuration based on the current
interaction context. For example, if Amazon Lex isn't able to understand user input, it uses a
clarification prompt message.

330
Amazon Lex Developer Guide
Amazon Lex Runtime Service

When you create an intent you can assign messages to groups. When messages are assigned to
groups Amazon Lex returns one message from each group in the response. The message field is
an escaped JSON string containing the messages. For more information about the structure of the
JSON string returned, see Supported Message Formats (p. 14).

If the Lambda function returns a message, Amazon Lex passes it to the client in its response.

Length Constraints: Minimum length of 1. Maximum length of 1024.


messageFormat (p. 329)

The format of the response message. One of the following values:


• PlainText - The message contains plain UTF-8 text.
• CustomPayload - The message is a custom format for the client.
• SSML - The message contains text formatted for voice output.
• Composite - The message contains an escaped JSON object containing one or more messages
from the groups that messages were assigned to when the intent was created.

Valid Values: PlainText | CustomPayload | SSML | Composite


sessionAttributes (p. 329)

Map of key/value pairs representing the session-specific context information.


slots (p. 329)

Map of zero or more intent slots (name/value pairs) Amazon Lex detected from the user input during
the conversation.

Amazon Lex creates a resolution list containing likely values for a slot. The value that it returns
is determined by the valueSelectionStrategy selected when the slot type was created or
updated. If valueSelectionStrategy is set to ORIGINAL_VALUE, the value provided by the user
is returned, if the user value is similar to the slot values. If valueSelectionStrategy is set to
TOP_RESOLUTION Amazon Lex returns the first value in the resolution list or, if there is no resolution
list, null. If you don't specify a valueSelectionStrategy, the default is ORIGINAL_VALUE.
slotToElicit (p. 329)

If the dialogState value is ElicitSlot, returns the name of the slot for which Amazon Lex is
eliciting a value.

The response returns the following as the HTTP body.

audioStream (p. 329)

The prompt (or statement) to convey to the user. This is based on the bot configuration
and context. For example, if Amazon Lex did not understand the user intent, it sends the
clarificationPrompt configured for the bot. If the intent requires confirmation before taking
the fulfillment action, it sends the confirmationPrompt. Another example: Suppose that the
Lambda function successfully fulfilled the intent, and sent a message to convey to the user. Then
Amazon Lex sends that message in the response.

Errors
BadGatewayException

Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS
Lambda) failed with an internal service error.

HTTP Status Code: 502

331
Amazon Lex Developer Guide
Amazon Lex Runtime Service

BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in
progress, or contains unbuilt changes.

HTTP Status Code: 400


ConflictException

Two clients are using the same AWS account, Amazon Lex bot, and user ID.

HTTP Status Code: 409


DependencyFailedException

One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example,
• If Amazon Lex does not have sufficient permissions to call a Lambda function.
• If a Lambda function takes longer than 30 seconds to execute.
• If a fulfillment Lambda function returns a Delegate dialog action without removing any slot
values.

HTTP Status Code: 424


InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500


LimitExceededException

Exceeded a limit.

HTTP Status Code: 429


LoopDetectedException

This exception is not used.

HTTP Status Code: 508


NotAcceptableException

The accept header in the request does not have a valid value.

HTTP Status Code: 406


NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404


RequestTimeoutException

The input speech is too long.

HTTP Status Code: 408


UnsupportedMediaTypeException

The Content-Type header (PostContent API) has an invalid value.

HTTP Status Code: 415

332
Amazon Lex Developer Guide
Amazon Lex Runtime Service

Example
Example 1

In this request, the URI identifies a bot (Traffic), bot version ($LATEST), and end user name (someuser).
The Content-Type header identifies the format of the audio in the body. Amazon Lex also supports
other formats. To convert audio from one format to another, if necessary, you can use SoX open source
software. You specify the format in which you want to get the response by adding the Accept HTTP
header.

In the response, the x-amz-lex-message header shows the response that Amazon Lex returned. The
client can then send this response to the user. The same message is sent in audio/MPEG format through
chunked encoding (as requested).

Sample Request

"POST /bot/Traffic/alias/$LATEST/user/someuser/content HTTP/1.1[\r][\n]"


"x-amz-lex-session-attributes: eyJ1c2VyTmFtZSI6IkJvYiJ9[\r][\n]"
"Content-Type: audio/x-l16; channel-count=1; sample-rate=16000f[\r][\n]"
"Accept: audio/mpeg[\r][\n]"
"Host: runtime.lex.us-east-1.amazonaws.com[\r][\n]"
"Authorization: AWS4-HMAC-SHA256 Credential=BLANKED_OUT/20161230/us-east-1/lex/
aws4_request,
SignedHeaders=accept;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-lex-session-
attributes, Signature=78ca5b54ea3f64a17ff7522de02cd90a9acd2365b45a9ce9b96ea105bb1c7ec2[\r]
[\n]"
"X-Amz-Date: 20161230T181426Z[\r][\n]"
"X-Amz-Content-Sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855[\r]
[\n]"
"Transfer-Encoding: chunked[\r][\n]"
"Connection: Keep-Alive[\r][\n]"
"User-Agent: Apache-HttpClient/4.5.x (Java/1.8.0_112)[\r][\n]"
"Accept-Encoding: gzip,deflate[\r][\n]"
"[\r][\n]"
"1000[\r][\n]"
"[0x7][0x0][0x7][0x0][\n]"
"[0x0][0x7][0x0][0xfc][0xff][\n]"
"[0x0][\n]"

Sample Response

"HTTP/1.1 200 OK[\r][\n]"


"x-amzn-RequestId: cc8b34af-cebb-11e6-a35c-55f3a992f28d[\r][\n]"
"x-amz-lex-message: Sorry, can you repeat that?[\r][\n]"
"x-amz-lex-dialog-state: ElicitIntent[\r][\n]"
"x-amz-lex-session-attributes: eyJ1c2VyTmFtZSI6IkJvYiJ9[\r][\n]"
"Content-Type: audio/mpeg[\r][\n]"
"Transfer-Encoding: chunked[\r][\n]"
"Date: Fri, 30 Dec 2016 18:14:28 GMT[\r][\n]"
"[\r][\n]"
"2000[\r][\n]"
"ID3[0x4][0x0][0x0][0x0][0x0][0x0]#TSSE[0x0][0x0][0x0][0xf][0x0][0x0]
[0x3]Lavf57.41.100[0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0xff]
[0xf3]`[0xc4][0x0][0x1b]{[0x8d][0xe8][0x1]C[0x18][0x1][0x0]J[0xe0]`b[0xdd][0xd1][0xb]
[0xfd][0x11][0xdf][0xfe]";[0xbb][0xbb][0x9f][0xee][0xee][0xee][0xee]|DDD/[0xff][0xff]
[0xff][0xff]www?D[0xf7]w^?[0xff][0xfa]h[0x88][0x85][0xfe][0x88][0x88][0x88][[0xa2]'[0xff]
[0xfa]"{[0x9f][0xe8][0x88]]D[0xeb][0xbb][0xbb][0xa2]!u[0xfd][0xdd][0xdf][0x88][0x94]
[0x0]F[0xef][0xa1]8[0x0][0x82]w[0x88]N[0x0][0x0][0x9b][0xbb][0xe8][0xe

333
Amazon Lex Developer Guide
Amazon Lex Runtime Service

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

334
Amazon Lex Developer Guide
Amazon Lex Runtime Service

PostText
Service: Amazon Lex Runtime Service

Sends user input (text or SSML) to Amazon Lex. Client applications can use this API to send requests to
Amazon Lex at runtime. Amazon Lex then interprets the user input using the machine learning model it
built for the bot.

In response, Amazon Lex returns the next message to convey to the user an optional responseCard to
display. Consider the following example messages:

• For a user input "I would like a pizza", Amazon Lex might return a response with a message eliciting
slot data (for example, PizzaSize): "What size pizza would you like?"
• After the user provides all of the pizza order information, Amazon Lex might return a response with a
message to obtain user confirmation "Proceed with the pizza order?".
• After the user replies to a confirmation prompt with a "yes", Amazon Lex might return a conclusion
statement: "Thank you, your cheese pizza has been ordered.".

Not all Amazon Lex messages require a user response. For example, a conclusion statement does
not require a response. Some messages require only a "yes" or "no" user response. In addition to the
message, Amazon Lex provides additional context about the message in the response that you might
use to enhance client behavior, for example, to display the appropriate client user interface. These
are the slotToElicit, dialogState, intentName, and slots fields in the response. Consider the
following examples:

• If the message is to elicit slot data, Amazon Lex returns the following context information:
• dialogState set to ElicitSlot
• intentName set to the intent name in the current context
• slotToElicit set to the slot name for which the message is eliciting information
• slots set to a map of slots, configured for the intent, with currently known values
• If the message is a confirmation prompt, the dialogState is set to ConfirmIntent and
SlotToElicit is set to null.
• If the message is a clarification prompt (configured for the intent) that indicates that user intent is not
understood, the dialogState is set to ElicitIntent and slotToElicit is set to null.

In addition, Amazon Lex also returns your application-specific sessionAttributes. For more
information, see Managing Conversation Context.

Request Syntax

POST /bot/botName/alias/botAlias/user/userId/text HTTP/1.1


Content-type: application/json

{
"inputText": "string",
"requestAttributes": {
"string" : "string"
},
"sessionAttributes": {
"string" : "string"
}
}

URI Request Parameters


The request requires the following URI parameters.

335
Amazon Lex Developer Guide
Amazon Lex Runtime Service

botAlias (p. 335)

The alias of the Amazon Lex bot.


botName (p. 335)

The name of the Amazon Lex bot.


userId (p. 335)

The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your
bot. At runtime, each request must contain the userID field.

To decide the user ID to use for your application, consider the following factors.
• The userID field must not contain any personally identifiable information of the user, for
example, name, personal identification numbers, or other end user personal information.
• If you want a user to start a conversation on one device and continue on another device, use a
user-specific identifier.
• If you want the same user to be able to have two independent conversations on two different
devices, choose a device-specific identifier.
• A user can't have two independent conversations with two different versions of the same bot. For
example, a user can't have a conversation with the PROD and BETA versions of the same bot. If
you anticipate that a user will need to have conversation with two different versions, for example,
while testing, include the bot alias in the user ID to separate the two conversations.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Request Body
The request accepts the following data in JSON format.

inputText (p. 335)

The text that the user entered (Amazon Lex interprets this text).

When you are using the AWS CLI, you can't pass a URL in the --input-text parameter. Pass the
URL using the --cli-input-json parameter instead.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1024.

Required: Yes
requestAttributes (p. 335)

Request-specific information passed between Amazon Lex and a client application.

The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes
with the prefix x-amz-lex:.

For more information, see Setting Request Attributes.

Type: String to string map

Required: No
sessionAttributes (p. 335)

Application-specific information passed between Amazon Lex and a client application.

336
Amazon Lex Developer Guide
Amazon Lex Runtime Service

For more information, see Setting Session Attributes.

Type: String to string map

Required: No

Response Syntax

HTTP/1.1 200
Content-type: application/json

{
"dialogState": "string",
"intentName": "string",
"message": "string",
"messageFormat": "string",
"responseCard": {
"contentType": "string",
"genericAttachments": [
{
"attachmentLinkUrl": "string",
"buttons": [
{
"text": "string",
"value": "string"
}
],
"imageUrl": "string",
"subTitle": "string",
"title": "string"
}
],
"version": "string"
},
"sessionAttributes": {
"string" : "string"
},
"slots": {
"string" : "string"
},
"slotToElicit": "string"
}

Response Elements
If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

dialogState (p. 337)

Identifies the current state of the user interaction. Amazon Lex returns one of the following values
as dialogState. The client can optionally use this information to customize the user interface.
• ElicitIntent - Amazon Lex wants to elicit user intent.

For example, a user might utter an intent ("I want to order a pizza"). If Amazon Lex cannot infer
the user intent from this utterance, it will return this dialogState.
• ConfirmIntent - Amazon Lex is expecting a "yes" or "no" response.

For example, Amazon Lex wants user confirmation before fulfilling an intent.

337
Amazon Lex Developer Guide
Amazon Lex Runtime Service

Instead of a simple "yes" or "no," a user might respond with additional information. For example,
"yes, but make it thick crust pizza" or "no, I want to order a drink". Amazon Lex can process such
additional information (in these examples, update the crust type slot value, or change intent from
OrderPizza to OrderDrink).
• ElicitSlot - Amazon Lex is expecting a slot value for the current intent.

For example, suppose that in the response Amazon Lex sends this message: "What size pizza
would you like?". A user might reply with the slot value (e.g., "medium"). The user might also
provide additional information in the response (e.g., "medium thick crust pizza"). Amazon Lex can
process such additional information appropriately.
• Fulfilled - Conveys that the Lambda function configured for the intent has successfully fulfilled
the intent.
• ReadyForFulfillment - Conveys that the client has to fulfill the intent.
• Failed - Conveys that the conversation with the user failed.

This can happen for various reasons including that the user did not provide an appropriate
response to prompts from the service (you can configure how many times Amazon Lex can prompt
a user for specific information), or the Lambda function failed to fulfill the intent.

Type: String

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Fulfilled |


ReadyForFulfillment | Failed
intentName (p. 337)

The current user intent that Amazon Lex is aware of.

Type: String
message (p. 337)

The message to convey to the user. The message can come from the bot's configuration or from a
Lambda function.

If the intent is not configured with a Lambda function, or if the Lambda function returned
Delegate as the dialogAction.type its response, Amazon Lex decides on the next course
of action and selects an appropriate message from the bot's configuration based on the current
interaction context. For example, if Amazon Lex isn't able to understand user input, it uses a
clarification prompt message.

When you create an intent you can assign messages to groups. When messages are assigned to
groups Amazon Lex returns one message from each group in the response. The message field is
an escaped JSON string containing the messages. For more information about the structure of the
JSON string returned, see Supported Message Formats (p. 14).

If the Lambda function returns a message, Amazon Lex passes it to the client in its response.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1024.


messageFormat (p. 337)

The format of the response message. One of the following values:


• PlainText - The message contains plain UTF-8 text.
• CustomPayload - The message is a custom format defined by the Lambda function.
• SSML - The message contains text formatted for voice output.

338
Amazon Lex Developer Guide
Amazon Lex Runtime Service

• Composite - The message contains an escaped JSON object containing one or more messages
from the groups that messages were assigned to when the intent was created.

Type: String

Valid Values: PlainText | CustomPayload | SSML | Composite


responseCard (p. 337)

Represents the options that the user has to respond to the current prompt. Response Card can come
from the bot configuration (in the Amazon Lex console, choose the settings button next to a slot) or
from a code hook (Lambda function).

Type: ResponseCard (p. 371) object


sessionAttributes (p. 337)

A map of key-value pairs representing the session-specific context information.

Type: String to string map


slots (p. 337)

The intent slots that Amazon Lex detected from the user input in the conversation.

Amazon Lex creates a resolution list containing likely values for a slot. The value that it returns
is determined by the valueSelectionStrategy selected when the slot type was created or
updated. If valueSelectionStrategy is set to ORIGINAL_VALUE, the value provided by the user
is returned, if the user value is similar to the slot values. If valueSelectionStrategy is set to
TOP_RESOLUTION Amazon Lex returns the first value in the resolution list or, if there is no resolution
list, null. If you don't specify a valueSelectionStrategy, the default is ORIGINAL_VALUE.

Type: String to string map


slotToElicit (p. 337)

If the dialogState value is ElicitSlot, returns the name of the slot for which Amazon Lex is
eliciting a value.

Type: String

Errors
BadGatewayException

Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS
Lambda) failed with an internal service error.

HTTP Status Code: 502


BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in
progress, or contains unbuilt changes.

HTTP Status Code: 400


ConflictException

Two clients are using the same AWS account, Amazon Lex bot, and user ID.

HTTP Status Code: 409


DependencyFailedException

One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example,

339
Amazon Lex Developer Guide
Data Types

• If Amazon Lex does not have sufficient permissions to call a Lambda function.
• If a Lambda function takes longer than 30 seconds to execute.
• If a fulfillment Lambda function returns a Delegate dialog action without removing any slot
values.

HTTP Status Code: 424


InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500


LimitExceededException

Exceeded a limit.

HTTP Status Code: 429


LoopDetectedException

This exception is not used.

HTTP Status Code: 508


NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface


• AWS SDK for .NET
• AWS SDK for C++
• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for JavaScript
• AWS SDK for PHP V3
• AWS SDK for Python
• AWS SDK for Ruby V2

Data Types
The following data types are supported by Amazon Lex Model Building Service:

• BotAliasMetadata (p. 342)


• BotChannelAssociation (p. 344)
• BotMetadata (p. 346)
• BuiltinIntentMetadata (p. 348)
• BuiltinIntentSlot (p. 349)
• BuiltinSlotTypeMetadata (p. 350)

340
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• CodeHook (p. 351)


• EnumerationValue (p. 352)
• FollowUpPrompt (p. 353)
• FulfillmentActivity (p. 354)
• Intent (p. 355)
• IntentMetadata (p. 356)
• Message (p. 358)
• Prompt (p. 359)
• ResourceReference (p. 360)
• Slot (p. 361)
• SlotTypeMetadata (p. 363)
• Statement (p. 365)
• UtteranceData (p. 366)
• UtteranceList (p. 367)

The following data types are supported by Amazon Lex Runtime Service:

• Button (p. 368)


• GenericAttachment (p. 369)
• ResponseCard (p. 371)

Amazon Lex Model Building Service


The following data types are supported by Amazon Lex Model Building Service:

• BotAliasMetadata (p. 342)


• BotChannelAssociation (p. 344)
• BotMetadata (p. 346)
• BuiltinIntentMetadata (p. 348)
• BuiltinIntentSlot (p. 349)
• BuiltinSlotTypeMetadata (p. 350)
• CodeHook (p. 351)
• EnumerationValue (p. 352)
• FollowUpPrompt (p. 353)
• FulfillmentActivity (p. 354)
• Intent (p. 355)
• IntentMetadata (p. 356)
• Message (p. 358)
• Prompt (p. 359)
• ResourceReference (p. 360)
• Slot (p. 361)
• SlotTypeMetadata (p. 363)
• Statement (p. 365)
• UtteranceData (p. 366)
• UtteranceList (p. 367)

341
Amazon Lex Developer Guide
Amazon Lex Model Building Service

BotAliasMetadata
Service: Amazon Lex Model Building Service

Provides information about a bot alias.

Contents
botName

The name of the bot to which the alias points.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No
botVersion

The version of the Amazon Lex bot to which the alias points.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No
checksum

Checksum of the bot alias.

Type: String

Required: No
createdDate

The date that the bot alias was created.

Type: Timestamp

Required: No
description

A description of the bot alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
lastUpdatedDate

The date that the bot alias was updated. When you create a resource, the creation date and last
updated date are the same.

Type: Timestamp

Required: No

342
Amazon Lex Developer Guide
Amazon Lex Model Building Service

name

The name of the bot alias.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

343
Amazon Lex Developer Guide
Amazon Lex Model Building Service

BotChannelAssociation
Service: Amazon Lex Model Building Service

Represents an association between an Amazon Lex bot and an external messaging platform.

Contents
botAlias

An alias pointing to the specific version of the Amazon Lex bot to which this association is being
made.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No
botConfiguration

Provides information necessary to communicate with the messaging platform.

Type: String to string map

Required: No
botName

The name of the Amazon Lex bot to which this association is being made.
Note
Currently, Amazon Lex supports associations with Facebook and Slack, and Twilio.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No
createdDate

The date that the association between the Amazon Lex bot and the channel was created.

Type: Timestamp

Required: No
description

A text description of the association you are creating.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
failureReason

If status is FAILED, Amazon Lex provides the reason that it failed to create the association.

344
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Type: String

Required: No
name

The name of the association between the bot and the channel.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No
status

The status of the bot channel.


• CREATED - The channel has been created and is ready for use.
• IN_PROGRESS - Channel creation is in progress.
• FAILED - There was an error creating the channel. For information about the reason for the
failure, see the failureReason field.

Type: String

Valid Values: IN_PROGRESS | CREATED | FAILED

Required: No
type

Specifies the type of association by indicating the type of channel being established between the
Amazon Lex bot and the external messaging platform.

Type: String

Valid Values: Facebook | Slack | Twilio-Sms | Kik

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

345
Amazon Lex Developer Guide
Amazon Lex Model Building Service

BotMetadata
Service: Amazon Lex Model Building Service

Provides information about a bot. .

Contents
createdDate

The date that the bot was created.

Type: Timestamp

Required: No
description

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
lastUpdatedDate

The date that the bot was updated. When you create a bot, the creation date and last updated date
are the same.

Type: Timestamp

Required: No
name

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No
status

The status of the bot.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT

Required: No
version

The version of the bot. For a new bot, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

346
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

347
Amazon Lex Developer Guide
Amazon Lex Model Building Service

BuiltinIntentMetadata
Service: Amazon Lex Model Building Service

Provides metadata for a built-in intent.

Contents
signature

A unique identifier for the built-in intent. To find the signature for an intent, see Standard Built-in
Intents in the Alexa Skills Kit.

Type: String

Required: No
supportedLocales

A list of identifiers for the locales that the intent supports.

Type: Array of strings

Valid Values: en-US

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

348
Amazon Lex Developer Guide
Amazon Lex Model Building Service

BuiltinIntentSlot
Service: Amazon Lex Model Building Service

Provides information about a slot used in a built-in intent.

Contents
name

A list of the slots defined for the intent.

Type: String

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

349
Amazon Lex Developer Guide
Amazon Lex Model Building Service

BuiltinSlotTypeMetadata
Service: Amazon Lex Model Building Service

Provides information about a built in slot type.

Contents
signature

A unique identifier for the built-in slot type. To find the signature for a slot type, see Slot Type
Reference in the Alexa Skills Kit.

Type: String

Required: No
supportedLocales

A list of target locales for the slot.

Type: Array of strings

Valid Values: en-US

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

350
Amazon Lex Developer Guide
Amazon Lex Model Building Service

CodeHook
Service: Amazon Lex Model Building Service

Specifies a Lambda function that verifies requests to a bot or fulfills the user's request to a bot..

Contents
messageVersion

The version of the request-response that you want Amazon Lex to use to invoke your Lambda
function. For more information, see Using Lambda Functions (p. 101).

Type: String

Length Constraints: Minimum length of 1. Maximum length of 5.

Required: Yes
uri

The Amazon Resource Name (ARN) of the Lambda function.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: arn:aws:lambda:[a-z]+-[a-z]+-[0-9]:[0-9]{12}:function:[a-zA-Z0-9-
_]+(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?(:[a-zA-
Z0-9-_]+)?

Required: Yes

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

351
Amazon Lex Developer Guide
Amazon Lex Model Building Service

EnumerationValue
Service: Amazon Lex Model Building Service

Each slot type can have a set of values. Each enumeration value represents a value the slot type can take.

For example, a pizza ordering bot could have a slot type that specifies the type of crust that the pizza
should have. The slot type could include the values

• thick
• thin
• stuffed

Contents
synonyms

Additional values related to the slot type value.

Type: Array of strings

Length Constraints: Minimum length of 1. Maximum length of 140.

Required: No
value

The value of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 140.

Required: Yes

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

352
Amazon Lex Developer Guide
Amazon Lex Model Building Service

FollowUpPrompt
Service: Amazon Lex Model Building Service

A prompt for additional activity after an intent is fulfilled. For example, after the OrderPizza intent is
fulfilled, you might prompt the user to find out whether the user wants to order drinks.

Contents
prompt

Prompts for information from the user.

Type: Prompt (p. 359) object

Required: Yes
rejectionStatement

If the user answers "no" to the question defined in the prompt field, Amazon Lex responds with this
statement to acknowledge that the intent was canceled.

Type: Statement (p. 365) object

Required: Yes

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

353
Amazon Lex Developer Guide
Amazon Lex Model Building Service

FulfillmentActivity
Service: Amazon Lex Model Building Service

Describes how the intent is fulfilled after the user provides all of the information required for the intent.
You can provide a Lambda function to process the intent, or you can return the intent information to the
client application. We recommend that you use a Lambda function so that the relevant logic lives in the
Cloud and limit the client-side code primarily to presentation. If you need to update the logic, you only
update the Lambda function; you don't need to upgrade your client application.

Consider the following examples:

• In a pizza ordering application, after the user provides all of the information for placing an order, you
use a Lambda function to place an order with a pizzeria.
• In a gaming application, when a user says "pick up a rock," this information must go back to the
client application so that it can perform the operation and update the graphics. In this case, you want
Amazon Lex to return the intent data to the client.

Contents
codeHook

A description of the Lambda function that is run to fulfill the intent.

Type: CodeHook (p. 351) object

Required: No
type

How the intent should be fulfilled, either by running a Lambda function or by returning the slot data
to the client application.

Type: String

Valid Values: ReturnIntent | CodeHook

Required: Yes

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

354
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Intent
Service: Amazon Lex Model Building Service

Identifies the specific version of an intent.

Contents
intentName

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes
intentVersion

The version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

355
Amazon Lex Developer Guide
Amazon Lex Model Building Service

IntentMetadata
Service: Amazon Lex Model Building Service

Provides information about an intent.

Contents
createdDate

The date that the intent was created.

Type: Timestamp

Required: No
description

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
lastUpdatedDate

The date that the intent was updated. When you create an intent, the creation date and last updated
date are the same.

Type: Timestamp

Required: No
name

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No
version

The version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++

356
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Go


• AWS SDK for Java
• AWS SDK for Ruby V2

357
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Message
Service: Amazon Lex Model Building Service

The message object that provides the message text and its type.

Contents
content

The text of the message.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1000.

Required: Yes
contentType

The content type of the message string.

Type: String

Valid Values: PlainText | SSML | CustomPayload

Required: Yes
groupNumber

Identifies the message group that the message belongs to. When a group is assigned to a message,
Amazon Lex returns one message from each group in the response.

Type: Integer

Valid Range: Minimum value of 1. Maximum value of 5.

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

358
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Prompt
Service: Amazon Lex Model Building Service

Obtains information from the user. To define a prompt, provide one or more messages and specify the
number of attempts to get information from the user. If you provide more than one message, Amazon
Lex chooses one of the messages to use to prompt the user. For more information, see Amazon Lex: How
It Works (p. 3).

Contents
maxAttempts

The number of times to prompt the user for information.

Type: Integer

Valid Range: Minimum value of 1. Maximum value of 5.

Required: Yes
messages

An array of objects, each of which provides a message string and its type. You can specify the
message string in plain text or in Speech Synthesis Markup Language (SSML).

Type: Array of Message (p. 358) objects

Array Members: Minimum number of 1 item. Maximum number of 15 items.

Required: Yes
responseCard

A response card. Amazon Lex uses this prompt at runtime, in the PostText API response. It
substitutes session attributes and slot values for placeholders in the response card. For more
information, see Example: Using a Response Card (p. 170).

Type: String

Length Constraints: Minimum length of 1. Maximum length of 50000.

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

359
Amazon Lex Developer Guide
Amazon Lex Model Building Service

ResourceReference
Service: Amazon Lex Model Building Service

Describes the resource that refers to the resource that you are attempting to delete. This object is
returned as part of the ResourceInUseException exception.

Contents
name

The name of the resource that is using the resource that you are trying to delete.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+

Required: No
version

The version of the resource that is using the resource that you are trying to delete.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

360
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Slot
Service: Amazon Lex Model Building Service

Identifies the version of a specific slot.

Contents
description

A description of the slot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
name

The name of the slot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z](-|_|.)?)+$

Required: Yes
priority

Directs Lex the order in which to elicit this slot value from the user. For example, if the intent has
two slots with priorities 1 and 2, AWS Lex first elicits a value for the slot with priority 1.

If multiple slots share the same priority, the order in which Lex elicits values is arbitrary.

Type: Integer

Valid Range: Minimum value of 0. Maximum value of 100.

Required: No
responseCard

A set of possible responses for the slot type used by text-based clients. A user chooses an option
from the response card, instead of using text to reply.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 50000.

Required: No
sampleUtterances

If you know a specific pattern with which users might respond to an Amazon Lex request for a slot
value, you can provide those utterances to improve accuracy. This is optional. In most cases, Amazon
Lex is capable of understanding user utterances.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Length Constraints: Minimum length of 1. Maximum length of 200.

361
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Required: No
slotConstraint

Specifies whether the slot is required or optional.

Type: String

Valid Values: Required | Optional

Required: Yes
slotType

The type of the slot, either a custom slot type that you defined or one of the built-in slot types.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^((AMAZON\.)_?|[A-Za-z]_?)+

Required: No
slotTypeVersion

The version of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No
valueElicitationPrompt

The prompt that Amazon Lex uses to elicit the slot value from the user.

Type: Prompt (p. 359) object

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

362
Amazon Lex Developer Guide
Amazon Lex Model Building Service

SlotTypeMetadata
Service: Amazon Lex Model Building Service

Provides information about a slot type..

Contents
createdDate

The date that the slot type was created.

Type: Timestamp

Required: No
description

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No
lastUpdatedDate

The date that the slot type was updated. When you create a resource, the creation date and last
updated date are the same.

Type: Timestamp

Required: No
name

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No
version

The version of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++

363
Amazon Lex Developer Guide
Amazon Lex Model Building Service

• AWS SDK for Go


• AWS SDK for Java
• AWS SDK for Ruby V2

364
Amazon Lex Developer Guide
Amazon Lex Model Building Service

Statement
Service: Amazon Lex Model Building Service

A collection of messages that convey information to the user. At runtime, Amazon Lex selects the
message to convey.

Contents
messages

A collection of message objects.

Type: Array of Message (p. 358) objects

Array Members: Minimum number of 1 item. Maximum number of 15 items.

Required: Yes
responseCard

At runtime, if the client is using the PostText API, Amazon Lex includes the response card in the
response. It substitutes all of the session attributes and slot values for placeholders in the response
card.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 50000.

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

365
Amazon Lex Developer Guide
Amazon Lex Model Building Service

UtteranceData
Service: Amazon Lex Model Building Service

Provides information about a single utterance that was made to your bot.

Contents
count

The number of times that the utterance was processed.

Type: Integer

Required: No
distinctUsers

The total number of individuals that used the utterance.

Type: Integer

Required: No
firstUtteredDate

The date that the utterance was first recorded.

Type: Timestamp

Required: No
lastUtteredDate

The date that the utterance was last recorded.

Type: Timestamp

Required: No
utteranceString

The text that was entered by the user or the text representation of an audio clip.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2000.

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

366
Amazon Lex Developer Guide
Amazon Lex Runtime Service

UtteranceList
Service: Amazon Lex Model Building Service

Provides a list of utterances that have been made to a specific version of your bot. The list contains a
maximum of 100 utterances.

Contents
botVersion

The version of the bot that processed the list.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No
utterances

One or more UtteranceData (p. 366) objects that contain information about the utterances that have
been made to a bot. The maximum number of object is 100.

Type: Array of UtteranceData (p. 366) objects

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

Amazon Lex Runtime Service


The following data types are supported by Amazon Lex Runtime Service:

• Button (p. 368)


• GenericAttachment (p. 369)
• ResponseCard (p. 371)

367
Amazon Lex Developer Guide
Amazon Lex Runtime Service

Button
Service: Amazon Lex Runtime Service

Represents an option to be shown on the client platform (Facebook, Slack, etc.)

Contents
text

Text that is visible to the user on the button.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 15.

Required: Yes
value

The value sent to Amazon Lex when a user chooses the button. For example, consider button text
"NYC." When the user chooses the button, the value sent can be "New York City."

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1000.

Required: Yes

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

368
Amazon Lex Developer Guide
Amazon Lex Runtime Service

GenericAttachment
Service: Amazon Lex Runtime Service

Represents an option rendered to the user when a prompt is shown. It could be an image, a button, a
link, or text.

Contents
attachmentLinkUrl

The URL of an attachment to the response card.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2048.

Required: No
buttons

The list of options to show to the user.

Type: Array of Button (p. 368) objects

Array Members: Minimum number of 0 items. Maximum number of 5 items.

Required: No
imageUrl

The URL of an image that is displayed to the user.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2048.

Required: No
subTitle

The subtitle shown below the title.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 80.

Required: No
title

The title of the option.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 80.

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++

369
Amazon Lex Developer Guide
Amazon Lex Runtime Service

• AWS SDK for Go


• AWS SDK for Java
• AWS SDK for Ruby V2

370
Amazon Lex Developer Guide
Amazon Lex Runtime Service

ResponseCard
Service: Amazon Lex Runtime Service

If you configure a response card when creating your bots, Amazon Lex substitutes the session attributes
and slot values that are available, and then returns it. The response card can also come from a Lambda
function ( dialogCodeHook and fulfillmentActivity on an intent).

Contents
contentType

The content type of the response.

Type: String

Valid Values: application/vnd.amazonaws.card.generic

Required: No
genericAttachments

An array of attachment objects representing options.

Type: Array of GenericAttachment (p. 369) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Required: No
version

The version of the response card format.

Type: String

Required: No

See Also
For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++


• AWS SDK for Go
• AWS SDK for Java
• AWS SDK for Ruby V2

371
Amazon Lex Developer Guide

Document History for Amazon Lex


• Latest documentation update: May 8, 2018

The following table describes important changes in each release of Amazon Lex. For notification about
updates to this documentation, you can subscribe to an RSS feed.

update-history-change update-history-description update-history-date

Region expansion (p. 372) Amazon Lex is now available in May 8, 2018
US West (Oregon) (us-west-2).

New feature (p. 372) Added support for exporting February 13, 2018
and importing in Amazon Lex
format. For more information,
see Importing and Exporting
Amazon Lex Bots, Intents, and
Slot Types.

New feature (p. 372) Amazon Lex now supports February 8, 2018
additional response messages
for bots, For more information,
see Responses.

Region expansion (p. 372) Amazon Lex is now available in November 21, 2017
EU (Ireland) (eu-west-1).

New feature (p. 372) Added support for deploying November 20, 2017
Amazon Lex bots on Kik.
For more information, see
Integrating an Amazon Lex Bot
with Kik.

New feature (p. 372) Added support for new built-in November 3, 2017
slot types and request attributes.
For more information, see
Built-in Slot Types and Setting
Request Attributes .

New feature (p. 372) Added export to Alexa Skills Kit September 7, 2017
feature. For more information,
see Exporting to an Alexa Skill.

New feature (p. 372) Added synonym support for August 31, 2017
slot type values. For more
information, see Custom Slot
Types .

New feature (p. 372) Added AWS CloudTrail August 15, 2017
integration. For more
information, see Monitoring
Amazon Lex API Calls with AWS
CloudTrail Logs .

372
Amazon Lex Developer Guide

Expanded Added Getting Started examples May 22, 2017


documentation (p. 372) for the AWS CLI. For more
information, see https://
docs.aws.amazon.com/lex/
latest/dg/gs-cli.html

New guide (p. 372) This is the first release of the April 19, 2017
Amazon Lex User Guide.

373
Amazon Lex Developer Guide

AWS Glossary
For the latest AWS terminology, see the AWS Glossary in the AWS General Reference.

374

You might also like