

End of support notice: On September 15, 2025, AWS will discontinue support for Amazon Lex V1. After September 15, 2025, you will no longer be able to access the Amazon Lex V1 console or Amazon Lex V1 resources. If you are using Amazon Lex V2, refer to the [Amazon Lex V2 guide](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html) instead. . 

# Amazon Lex: How It Works
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.

1. Test the bot. You can use the test window client provided by the Amazon Lex console.

1. Publish a version and create an alias.

1. 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. Each bot must have a unique name within your account.

   

  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**. Intent names must be unique within your account.
  + **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](howitworks-builtins.md). 

   
+ **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.

   

  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. Each slot type must have a unique name within your account. 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](howitworks-builtins.md).

For a list of AWS Regions where Amazon Lex is available, see [AWS Regions and Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#lex_region) in the *Amazon Web Services General Reference*.

The following topics provide additional information. We recommend that you review them in order and then explore the [Getting Started with Amazon Lex](getting-started.md) exercises.

**Topics**
+ [

# Languages Supported in Amazon Lex
](how-it-works-language.md)
+ [

# Programming Model
](programming-model.md)
+ [

# Managing Messages
](howitworks-manage-prompts.md)
+ [

# Managing Conversation Context
](context-mgmt.md)
+ [

# Using Confidence Scores
](confidence-scores.md)
+ [

# Conversation Logs
](conversation-logs.md)
+ [

# Managing Sessions With the Amazon Lex API
](how-session-api.md)
+ [

# Bot Deployment Options
](chatbot-service.md)
+ [

# Built-in Intents and Slot Types
](howitworks-builtins.md)
+ [

# Custom Slot Types
](howitworks-custom-slots.md)
+ [

# Slot Obfuscation
](how-obfuscate.md)
+ [

# Sentiment Analysis
](sentiment-analysis.md)
+ [

# Tagging Your Amazon Lex Resources
](how-it-works-tags.md)

# Languages Supported in Amazon Lex
Supported Languages

Amazon Lex V1 supports a variety of languages and locales. The languages supported and the features that support them are listed in the following tables. 

Amazon Lex V2 supports additional languages, see [ Languages Supported in Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html)

<a name="topiclist"></a>

## Supported Languages and Locales


Amazon Lex V1 supports the following languages and locales.


| Code | Language and locale | 
| --- | --- | 
| de-DE | German (German) | 
| en-AU | English (Australia) | 
| en-GB | English (UK) | 
| en-IN | English (India) | 
| en-US | English (US) | 
| es-419 | Spanish (Latin America) | 
| es-ES | Spanish (Spain) | 
| es-US | Spanish (US) | 
| fr-CA | French (Canada) | 
| fr-FR | French (France) | 
| it-IT | Italian (Italy) | 
| ja-JP | Japanese (Japan) | 
| ko-KR | Korean (Korea) | 

## Languages and Locales Supported by Amazon Lex Features


All Amazon Lex features are supported in all languages and locales except as listed in this table.


| Feature | Supported languages and locales | 
| --- | --- | 
| [Setting Intent Context](context-mgmt-active-context.md) | English (US) (en-US) | 

# 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](https://docs.aws.amazon.com/lex/latest/dg/chatbot-service.html) 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**
+ [

## Model Building API Operations
](#programming-model-build-time-api)
+ [

## Runtime API Operations
](#programming-model-runtime-api)
+ [

## Lambda Functions As Code Hooks
](#prog-model-lambda)

## 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](API_PutBot.md), [PutBotAlias](API_PutBotAlias.md), [PutIntent](API_PutIntent.md), and [PutSlotType](API_PutSlotType.md) to create and update bots, bot aliases, intents, and slot types, respectively.
+ [CreateBotVersion](API_CreateBotVersion.md), [CreateIntentVersion](API_CreateIntentVersion.md), and [CreateSlotTypeVersion](API_CreateSlotTypeVersion.md) to create and publish versions of your bots, intents, and slot types, respectively.
+ [GetBot](API_GetBot.md) and [GetBots](API_GetBots.md) to get a specific bot or a list of bots that you have created, respectively.
+ [GetIntent](API_GetIntent.md) and [GetIntents](API_GetIntents.md) to get a specific intent or a list of intents that you have created, respectively.
+ [GetSlotType](API_GetSlotType.md) and [GetSlotTypes](API_GetSlotTypes.md) to get a specific slot type or a list of slot types that you have created, respectively.
+ [GetBuiltinIntent](API_GetBuiltinIntent.md), [GetBuiltinIntents](API_GetBuiltinIntents.md), and [GetBuiltinSlotTypes](API_GetBuiltinSlotTypes.md) 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](API_GetBotChannelAssociation.md) and [GetBotChannelAssociations](API_GetBotChannelAssociations.md) 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](API_DeleteBot.md), [DeleteBotAlias](API_DeleteBotAlias.md), [DeleteBotChannelAssociation](API_DeleteBotChannelAssociation.md), [DeleteIntent](API_DeleteIntent.md), and [DeleteSlotType](API_DeleteSlotType.md) 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](API_PutBot.md), [PutBotAlias](API_PutBotAlias.md) [PutIntent](API_PutIntent.md), or [PutSlotType](API_PutSlotType.md)—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](API_GetBot.md), [GetIntent](API_GetIntent.md), and [GetSlotType](API_GetSlotType.md)—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](API_runtime_PostContent.md) – 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:

   

  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](API_runtime_PostText.md) – 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](API_runtime_PostContent.md) 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](API_runtime_PostContent.md) API to send text and speech requests to Amazon Lex. You use this test window in the [Getting Started with Amazon Lex](getting-started.md) 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:

![\[The Amazon Lex console showing Lambda function code hooks.\]](http://docs.aws.amazon.com/lex/latest/dg/images/how-works-10.png)


You can also set the code hooks using the `dialogCodeHook` and `fulfillmentActivity` fields in the [PutIntent](API_PutIntent.md) 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 run 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. If you have a clarification prompt defined, 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](using-lambda.md).

# Managing Messages


**Topics**
+ [

## Types of Messages
](#msg-prompts-msg-types)
+ [

## Contexts for Configuring Messages
](#msg-prompts-context-for-msgs)
+ [

## Supported Message Formats
](#msg-prompts-formats)
+ [

## Message Groups
](#message-groups)
+ [

## Response Cards
](#msg-prompts-resp-card)

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, session attributes, and request 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:

```
[SessionAttributeName] 
```

To refer to request attributes, use the following syntax:

```
((RequestAttributeName)) 
```

Messages can include both slot values, session attributes and request 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 (\$1\$1) in a message, use the backslash (\$1) 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](API_runtime_PostText.md) and [PostContent](API_runtime_PostContent.md). For an example, see [Book Trip](ex-book-trip.md). 

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](#msg-prompts-formats).

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 session end 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 sending the session end message. You configure bot-level messages in the **Error Handling** section of the Amazon Lex console, as in the following image:

![\[Error handling section in the editor tab of the console. Clarification prompts and a hang-up phrase may be specified.\]](http://docs.aws.amazon.com/lex/latest/dg/images/how-works-20.png)


With the API, you configure messages by setting the `clarificationPrompt` and `abortStatement` fields in the [PutBot](API_PutBot.md) 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](API_PutIntent.md) operation. For more information, see [Message Groups](#message-groups).

### 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](#message-groups). 

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 the following:

![\[One possible conversation with a bot.\]](http://docs.aws.amazon.com/lex/latest/dg/images/default-response-10b.png)


Another one could be the following:

![\[Another possible conversation with a bot.\]](http://docs.aws.amazon.com/lex/latest/dg/images/default-response-20c.png)


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. The following image provides an example:

![\[Follow-up prompt in a conversation with a bot.\]](http://docs.aws.amazon.com/lex/latest/dg/images/default-response-25a.png)


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." See the following image for an example:

![\[Message configuration for when a user says "no".\]](http://docs.aws.amazon.com/lex/latest/dg/images/default-response-30b.png)


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 `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](API_runtime_PostText.md) operation, or when you use the [PostContent](API_runtime_PostContent.md) 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](#message-groups).

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](context-mgmt-request-attribs.md#special-response).

## 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](#msg-prompts-response).

To create a message group, you can use the console or you can use the [PutBot](API_PutBot.md), [PutIntent](API_PutIntent.md), or [PutSlotType](API_PutSlotType.md) 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](API_PutIntent.md) 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:
+ 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](context-mgmt-request-attribs.md#special-response).

## Response Cards


**Note**  
Response cards do not work with Amazon Connect chat. However, see [ Add interactive messages to chat](https://docs.aws.amazon.com/connect/latest/adminguide/interactive-messages.html) for similar functionality.

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. See the following image:

![\[An example response card.\]](http://docs.aws.amazon.com/lex/latest/dg/images/resp-console-5.png)


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](API_PutIntent.md) operation. Or you can define a dynamic response card 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](API_runtime_PostText.md) 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](https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template) on the Facebook website. For an example of the JSON structure, see [Generating Response Cards Dynamically](#msg-prompts-resp-card-dynamic).

You can use response cards only with the [PostText](API_runtime_PostText.md) operation. You can't use response cards with the [PostContent](API_runtime_PostContent.md) operation. 

### Defining Static Response Cards


Define static response cards with the [PutBot](API_PutBot.md) 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:

![\[The intent editor in the console.\]](http://docs.aws.amazon.com/lex/latest/dg/images/resp-console-10a.png)


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

![\[The console showing the response card editor.\]](http://docs.aws.amazon.com/lex/latest/dg/images/resp-console-20a.png)


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:

![\[A response card in Facebook Messenger.\]](http://docs.aws.amazon.com/lex/latest/dg/images/resp-fb-exampleA.png)


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](context-mgmt-session-attribs.md). For an example, see [Using a Response Card](ex-resp-card.md).

### 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](lambda-input-response-format.md#using-lambda-response-format). 

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": [
        {
          "text": "Lemon",
          "value": "lemon"
        },
        {
          "text": "Raspberry",
          "value": "raspberry"
        },
        {
          "text": "Plain",
          "value": "plain"
        }
      ]
    }
  ]
}
```

For an example, see [Schedule Appointment](ex1-sch-appt.md).

# 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 Intent Context
](context-mgmt-active-context.md)
+ [

# Using Default Slot Values
](context-mgmt-default.md)
+ [

# Setting Session Attributes
](context-mgmt-session-attribs.md)
+ [

# Setting Request Attributes
](context-mgmt-request-attribs.md)
+ [

# Setting the Session Timeout
](context-mgmt-session-timeout.md)
+ [

# Sharing Information Between Intents
](context-mgmt-cross-intent.md)
+ [

# Setting Complex Attributes
](context-mgmt-complex-attributes.md)

# Setting Intent Context


You can have Amazon Lex trigger intents based on *context*. A *context* is a state variable that can be associated with an intent when you define a bot.

You configure the contexts for an intent when you create the intent using the console or using the [PutIntent](API_PutIntent.md) operation. You can only use contexts in the English (US) (en-US) locale, and only if you set the `enableModelImprovements` parameter to `true` when you created the bot with the [PutBot](API_PutBot.md) operation.

There are two types of relationships for contexts, output contexts and input contexts. An *output context* becomes active when an associated intent is fulfilled. An output context is returned to your application in the response from the [PostText](API_runtime_PostText.md) or [PostContent](API_runtime_PostContent.md) operation, and it is set for the current session. After a context is activated, it stays active for the number of turns or time limit configured when the context was defined. 

An *input context* specifies conditions under which an intent can be recognized. An intent can only be recognized during a conversation when all of its input contexts are active. An intent with no input contexts is always eligible for recognition. 

Amazon Lex automatically manages the lifecycle of contexts that are activated by fulfilling intents with output contexts. You can also set active contexts in a call to the `PostContent` or `PostText` operation.

You can also set the context of a conversation using the Lambda function for the intent. The output context from Amazon Lex is sent to the Lambda function input event. The Lambda function can send contexts in its response. For more information, see [Lambda Function Input Event and Response Format](lambda-input-response-format.md).

For example, suppose you have an intent to book a rental car that is configured to return an output context called "book\$1car\$1fulfilled". When the intent is fulfilled, Amazon Lex sets the output context variable "book\$1car\$1fulfilled". Since "book\$1car\$1fulfilled" is an active context, an intent with the "book\$1car\$1fulfilled" context set as an input context is now considered for recognition, as long as a user utterance is recognized as an attempt to elicit that intent. You can use this for intents that only make sense after booking a car, such as emailing a receipt or modifying a reservation.

## Output Context


Amazon Lex makes an intent's output contexts active when the intent is fulfilled. You can use the output context to control the intents eligible to follow up the current intent.

Each context has a list of parameters that are maintained in the session. The parameters are the slot values for the fulfilled intent. You can use these parameters to pre-populate slot values for other intents. For more information,see [Using Default Slot Values](context-mgmt-default.md).

You configure the output context when you create an intent with the console or with the [PutIntent](API_PutIntent.md) operation. You can configure an intent with more than one output context. When the intent is fulfilled, all of the output contexts are activated and returned in the [PostText](API_runtime_PostText.md) or [PostContent](API_runtime_PostContent.md) response.

The following shows assigning an output context to an intent using the console.

![\[Output tag labeled order_complete with a time to live of 5 turns or 90 seconds.\]](http://docs.aws.amazon.com/lex/latest/dg/images/context-output.png)


When you define an output context you also define its *time to live*, the length of time or number of turns that the context is included in responses from Amazon Lex. A *turn* is one request from your application to Amazon Lex. Once the number of turns or the time has expired, the context is no longer active. 

Your application can use the output context as needed. For example, your application can use the output context to:
+ Change the behavior of the application based on the context. For example, a travel application could have a different action for the context "book\$1car\$1fulfilled" than "rental\$1hotel\$1fulfilled."
+ Return the output context to Amazon Lex as the input context for the next utterance. If Amazon Lex recognizes the utterance as an attempt to elicit an intent, it uses the context to limit the intents that can be returned to ones with the specified context.

## Input Context


You set an input context to limit the points in the conversation where the intent is recognized. Intents without an input context are always eligible to be recognized.

You set the input contexts that an intent responds to using the console or the `PutIntent` operation. An intent can have more than one input context. The following shows assigning an input context to an intent using the console.

![\[Input tag labeled order_complete.\]](http://docs.aws.amazon.com/lex/latest/dg/images/context-input.png)


For an intent with more than one input context, all contexts must be active to trigger the intent. You can set an input context when you call the [PostText](API_runtime_PostText.md), [PostContent](API_runtime_PostContent.md), or [PutSession](API_runtime_PutSession.md) operation. 

You can configure the slots in an intent to take default values from the current active context. Default values are used when Amazon Lex recognizes a new intent but doesn't receive a slot value. You specify the context name and slot name in the form `#context-name.parameter-name` when you define the slot. For more information, see [Using Default Slot Values](context-mgmt-default.md).

# Using Default Slot Values


When you use a default value, you specify a source for a slot value to be filled for new intents when no slot is provided by the user’s input. This source can be previous dialog, request or session attributes, or a fixed value that you set at build-time. 

You can use the following as the source for your default values.
+ Previous dialog (contexts) – \$1context-name.parameter-name
+ Session attributes – [attribute-name]
+ Request attributes – <attribute-name>
+ Fixed value – Any value that doesn't match the previous

When you use the [PutIntent](API_PutIntent.md) operation to add slots to an intent, you can add a list of default values. Default values are used in the order that they are listed. For example, suppose you have an intent with a slot with the following definition:

```
"slots": [
    {
        "name": "reservation-start-date",
        "defaultValueSpec": {
            "defaultValueList": [
                {
                    "defaultValue": "#book-car-fulfilled.startDate"
                },
                {  
                    "defaultValue": "[reservationStartDate]"
                }
            ]
        },
        Other slot configuration settings
    }
]
```

When the intent is recognized, the slot named "reservation-start-date" has its value set to one of the following.

1. If the "book-car-fulfilled" context is active, the value of the "startDate" parameter is used as the default value.

1. If the "book-car-fulfilled" context is not active, or if the "startDate" parameter is not set, the value of the "reservationStartDate" session attribute is used as the default value.

1. If neither of the first two default values are used, then the slot doesn't have a default value and Amazon Lex will elicit a value as usual.

If a default value is used for the slot, the slot is not elicited even if it is required.

# 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)](gs-bp.md), 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)](gs-bp-details-after-lambda.md). 
+ In [Book Trip](ex-book-trip.md), 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](book-trip-detail-flow.md).

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](API_runtime_PostContent.md) or [PostText](API_runtime_PostText.md) operation. For example, `"Location": "111 Maple Street"`. The Lambda function uses this information to find the closest pizzeria to place the order.
+ 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](API_runtime_PostContent.md) or the [PostText](API_runtime_PostText.md) 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](context-mgmt-complex-attributes.md).

# 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 [PostContent](API_runtime_PostContent.md) or the `requestAttributes` field in a [PostText](API_runtime_PostText.md) 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.

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](example1.md).

### 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](API_runtime_PostContent.md) and [PostText](API_runtime_PostText.md) 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](howitworks-manage-prompts.md#message-groups).

**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\$1York  | 
| US West (Oregon) |  America/Los\$1Angeles  | 
| Asia Pacific (Singapore) |  Asia/Singapore  | 
| Asia Pacific (Sydney) |  Australia/Sydney  | 
| Asia Pacific (Tokyo) |  Asia/Tokyo  | 
| Europe (Frankfurt) |  Europe/Berlin  | 
| Europe (Ireland) |  Europe/Dublin  | 
| Europe (London) |  Europe/London  | 

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 your service is running in the US East (N. Virginia) Region and a person 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](https://en.wikipedia.org/wiki/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](context-mgmt-complex-attributes.md).

# 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](API_PutBot.md) operation by setting the [idleSessionTTLInSeconds](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-idleSessionTTLInSeconds) field.

# Sharing Information Between Intents


Amazon Lex supports sharing information between intents. To share between intents, use session 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 [Book Trip](ex-book-trip.md).

# 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](API_runtime_PostContent.md) and [PostText](API_runtime_PostText.md) 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);
```

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"
}
```

# Using Confidence Scores


When a user makes an utterance, Amazon Lex uses natural language understanding (NLU) to understand the user's request and return the proper intent. By default, Amazon Lex returns the most likely intent defined by your bot.

In some cases it may be difficult for Amazon Lex to determine the most likely intent. For example, the user might make an ambiguous utterance, or there might be two intents that are similar. To help determine the proper intent, you can combine your domain knowledge with the *confidence scores* of a list of alternative intents. A confidence score is a rating that Amazon Lex provides that shows how confident it is that an intent is the correct intent.

To determine the difference between two alternative intents, you can compare their confidence scores. For example, if one intent has a confidence score of 0.95 and another has a score of 0.65, the first intent is probably correct. However, if one intent has a score of 0.75 and another has a score of 0.72, there is ambiguity between the two intents that you may be able to discriminate using domain knowledge in your application.

You can also use confidence scores to create test applications that determine if changes to an intent's utterances make a difference in the behavior of the bot. For example, you can get the confidence scores for a bot's intents using a set of utterances, then update the intents with new utterances. You can then check the confidence scores to see if there was an improvement.

The confidence scores that Amazon Lex returns are comparative values. You should not rely on them as an absolute score. The values may change based on improvements to Amazon Lex.

When you use confidence scores, Amazon Lex returns the most likely intent and up to 4 alternative intents with their associated scores in each response. If all of the confidence scores are less than a threshold, Amazon Lex includes the `AMAZON.FallbackIntent`, the `AMAZON.KendraSearchIntent`, or both, if you have them configured. You can use the default threshold or you can set your own threshold.

The following JSON code shows the `alternativeIntents` field in the response from the [PostText](API_runtime_PostText.md) operation.

```
   "alternativeIntents": [ 
      { 
         "intentName": "string",
         "nluIntentConfidence": { 
            "score": number
         },
         "slots": { 
            "string" : "string" 
         }
      }
   ],
```

Set the threshold when you create or update a bot. You can use either the API or the Amazon Lex console. For the regions listed below you need to opt-in to enable accuracy improvements and confidence scores. In the console, choose confidence scores in the **Advanced Options** section. Using the API, set the `enableModelImprovements` parameter when you call the [PutBot](API_PutBot.md) operation. :
+ US East (N. Virginia) (us-east-1)
+ US West (Oregon) (us-west-2)
+ Asia Pacific (Sydney) (ap-southeast-2)
+ Europe (Ireland) (eu-west-1)

In all other regions, accuracy improvements and confidence score support is available by default.

To change the confidence threshold, set it in the console or using the [PutBot](API_PutBot.md) operation. The threshold must be a number between 1.00 and 0.00.

To use the console, set the confidence threshold when you create or update your bot.

**To set the confidence threshold when creating a bot (Console)**
+ On **Create your bot**, enter a value in the **Confidence score threshold** field.

**To update the confidence threshold (Console)**

1. From the list of your bots, choose the bot to update.

1. Choose the **Settings** tab.

1. In the left navigation, choose **General**.

1. Update the value in the **Confidence score threshold** field.

**To set or update the confidence threshold (SDK)**
+ Set the `nluIntentConfidenceThreshold` parameter of the [PutBot](API_PutBot.md) operation. The following JSON code shows the parameter being set.

  ```
     "nluIntentConfidenceThreshold": 0.75,
  ```

## Session Management


To change the intent that Amazon Lex uses in a conversation with the user, you can use the response from your dialog code hook Lambda function, or you can use the session management APIs in your custom application. 

### Using a Lambda function


When you use a Lambda function, Amazon Lex calls it with a JSON structure that contains the input to the function. The JSON structure contains a field called `currentIntent` that contains the intent that Amazon Lex has identified as the most likely intent for the user's utterance. The JSON structure also includes an `alternativeIntents` field that contains up to four additional intents that may satisfy the user's intent. Each intent includes a field called `nluIntentConfidenceScore` that contains the confidence score that Amazon Lex assigned to the intent.

To use an alternative intent, you specify it in the `ConfirmIntent` or the `ElicitSlot` dialog action in your Lambda function.

For more information, see [Using Lambda Functions](using-lambda.md).

### Using the Session Management API


To use a different intent from the current intent, use the [PutSession](API_runtime_PutSession.md) operation. For example, if you decide that the first alternative is preferable to the intent that Amazon Lex chose, you can use the `PutSession` operation to change intents so that the next intent that the user interacts with is the one that you selected.

For more information, see [Managing Sessions With the Amazon Lex API](how-session-api.md).

# Conversation Logs


You enable *conversation logs* to store bot interactions. You can use these logs to review the performance of your bot and to troubleshoot issues with conversations. You can log text for the [PostText](API_runtime_PostText.md) operation. You can log both text and audio for the [PostContent](API_runtime_PostContent.md) operation. By enabling conversation logs you get a detailed view of conversations that users have with your bot.

For example, a session with your bot has a session ID. You can use this ID to get the transcript of the conversation including user utterances and the corresponding bot responses. You also get metadata such as intent name and slot values for an utterance.

**Note**  
You can't use conversation logs with a bot subject to the Children's Online Privacy Protection Act (COPPA).

Conversation logs are configured for an alias. Each alias can have different settings for their text and audio logs. You can enable text logs, audio logs, or both for each alias. Text logs store text input, transcripts of audio input, and associated metadata in CloudWatch Logs. Audio logs store audio input in Amazon S3. You can enable encryption of text and audio logs using AWS KMS customer managed CMKs.

To configure logging, use the console or the [PutBotAlias](API_PutBotAlias.md) operation. You can't log conversations for the `$LATEST` alias of your bot or for the test bot available in the Amazon Lex console. After enabling conversation logs for an alias, [PostContent](API_runtime_PostContent.md) or [PostText](API_runtime_PostText.md) operation for that alias logs the text or audio utterances in the configured CloudWatch Logs log group or S3 bucket.

**Topics**
+ [

# IAM Policies for Conversation Logs
](conversation-logs-policies.md)
+ [

# Configuring Conversation Logs
](conversation-logs-configure.md)
+ [

# Encrypting Conversation Logs
](conversation-logs-encrypting.md)
+ [

# Viewing Text Logs in Amazon CloudWatch Logs
](conversation-logs-cw.md)
+ [

# Accessing Audio Logs in Amazon S3
](conversation-logs-s3.md)
+ [

# Monitoring Conversation Log Status with CloudWatch Metrics
](conversation-logs-monitoring.md)

# IAM Policies for Conversation Logs


Depending on the type of logging that you select, Amazon Lex requires permission to use Amazon CloudWatch Logs and Amazon Simple Storage Service (S3) buckets to store your logs. You must create AWS Identity and Access Management roles and permissions to enable Amazon Lex to access these resources. 

## Creating an IAM Role and Policies for Conversation Logs


To enable conversation logs, you must grant write permission for CloudWatch Logs and Amazon S3. If you enable object encryption for your S3 objects, you need to grant access permission to the AWS KMS keys used to encrypt the objects. 

You can use the IAM AWS Management Console, the IAM API, or the AWS Command Line Interface to create the role and policies. These instructions use the AWS CLI to create the role and policies. For information about creating policies with the console, see [ Creating policies on the JSON tab ](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html#access_policies_create-json-editor) in the *AWS Identity and Access Management User Guide*.

**Note**  
The following code is formatted for Linux and MacOS. For Windows, replace the Linux line continuation character (\$1) with a caret (^).



**To create an IAM role for conversation logs**

1. Create a document in the current directory called **LexConversationLogsAssumeRolePolicyDocument.json**, add the following code to it, and save it. This policy document adds Amazon Lex as a trusted entity to the role. This allows Lex to assume the role to deliver logs to the resources configured for conversation logs.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "lex.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
       }
     ]
   }
   ```

------

1. In the AWS CLI, run the following command to create the IAM role for conversation logs.

   ```
   aws iam create-role \
       --role-name role-name \
       --assume-role-policy-document file://LexConversationLogsAssumeRolePolicyDocument.json
   ```

Next, create and attach a policy to the role that enables Amazon Lex to write to CloudWatch Logs. 

**To create an IAM policy for logging conversation text to CloudWatch Logs**

1. Create a document in the current directory called **LexConversationLogsCloudWatchLogsPolicy.json**, add the following IAM policy to it, and save it.

1. In the AWS CLI, create the IAM policy that grants write permission to the CloudWatch Logs log group.

   ```
   aws iam create-policy \
       --policy-name cloudwatch-policy-name \
       --policy-document file://LexConversationLogsCloudWatchLogsPolicy.json
   ```

1. Attach the policy to the IAM role that you created for conversation logs.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::account-id:policy/cloudwatch-policy-name \
       --role-name role-name
   ```

If you are logging audio to an S3 bucket, create a policy that enables Amazon Lex to write to the bucket.

**To create an IAM policy for audio logging to an S3 bucket**

1. Create a document in the current directory called **LexConversationLogsS3Policy.json**, add the following policy to it, and save it.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
         {
             "Effect": "Allow",
             "Action": [
                 "s3:PutObject"
             ],
             "Resource": "arn:aws:s3:::bucket-name/*"
         }
     ]
   }
   ```

------

1. In the AWS CLI, create the IAM policy that grants write permission to your S3 bucket.

   ```
   aws iam create-policy \
       --policy-name s3-policy-name \
       --policy-document file://LexConversationLogsS3Policy.json
   ```

1. Attach the policy to the role that you created for conversation logs.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::account-id:policy/s3-policy-name \
       --role-name role-name
   ```

## Granting Permission to Pass an IAM Role


When you use the console, the AWS Command Line Interface, or an AWS SDK to specify an IAM role to use for conversation logs, the user specifying the conversation logs IAM role must have permission to pass the role to Amazon Lex. To allow the user to pass the role to Amazon Lex, you must grant `PassRole` permission to the user, role, or group. 

The following policy defines the permission to grant to the user, role, or group. You can use the `iam:AssociatedResourceArn` and `iam:PassedToService` condition keys to limit the scope of the permission. For more information, see [ Granting a User Permissions to Pass a Role to an AWS Service ](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html) and [ IAM and AWS STS Condition Context Keys ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/role-name",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "lex.amazonaws.com"
                },
                "StringLike": {
                    "iam:AssociatedResourceARN": "arn:aws:lex:region:123456789012:bot:bot-name:bot-alias"
                }
            }
        }
    ]
}
```

------

# Configuring Conversation Logs


You enable and disable conversation logs using the console or the `conversationLogs` field of the `PutBotAlias` operation. You can turn on or turn off audio logs, text logs, or both. Logging starts on new bot sessions. Changes to log settings aren't reflected for active sessions.

To store text logs, use an Amazon CloudWatch Logs log group in your AWS account. You can use any valid log group. The log group must be in the same region as the Amazon Lex bot. For more information about creating a CloudWatch Logs log group, see [ Working with Log Groups and Log Streams ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html) in the *Amazon CloudWatch Logs User Guide*.

To store audio logs, use an Amazon S3 bucket in your AWS account. You can use any valid S3 bucket. The bucket must be in the same region as the Amazon Lex bot. For more information about creating an S3 bucket, see [ Create a Bucket ](https://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html) in the *Amazon Simple Storage Service Getting Started Guide*.

You must provide an IAM role with policies that enable Amazon Lex to write to the configured log group or bucket. For more information, see [Creating an IAM Role and Policies for Conversation Logs](conversation-logs-policies.md#conversation-logs-role-and-policy).

If you create a service-linked role using the AWS Command Line Interface, you must add a custom suffix to the role using the `custom-suffix` option as follows:

```
aws iam create-service-linked-role \
    --aws-service-name lex.amazon.aws.com \
    --custom-suffix suffix
```

The IAM role that you use to enable conversation logs must have the `iam:PassRole` permission. The following policy should be attached to the role.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/role"
        }
    ]
}
```

------

## Enabling Conversation Logs


**To turn on logs using the console**

1. Open the Amazon Lex console [https://console.aws.amazon.com/lex](https://console.aws.amazon.com/lex).

1. From the list, choose a bot.

1. Choose the **Settings** tab, and then from the left menu choose **Conversation logs**.

1. In the list of aliases, choose the settings icon for the alias for which you want to configure conversation logs.

1. Select whether to log text, audio, or both. 

1. For text logging, enter the Amazon CloudWatch Logs log group name.

1. For audio logging, enter the S3 bucket information.

1. Optional. To encrypt audio logs, choose the AWS KMS key to use for encryption.

1. Choose an IAM role with the required permissions.

1. Choose **Save** to start logging conversations.

**To turn on text logs using the API**

1. Call the [PutBotAlias](API_PutBotAlias.md) operation with an entry in the `logSettings` member of the `conversationLogs` field
   + Set the `destination` member to `CLOUDWATCH_LOGS`
   + Set the `logType` member to `TEXT`
   + Set the `resourceArn` member to the Amazon Resource Name (ARN) of the CloudWatch Logs log group that is the destination for the logs

1. Set the `iamRoleArn` member of the `conversationLogs` field to the Amazon Resource Name (ARN) of an IAM role that has the required permissions for enabling conversation logs on the specified resources.

**To turn on audio logs using the API**

1. Call the [PutBotAlias](API_PutBotAlias.md) operation with an entry in the `logSettings` member of the `conversationLogs` field
   + Set the `destination` member to `S3`
   + Set the `logType` member to `AUDIO`
   + Set the `resourceArn` member to the ARN of the Amazon S3 bucket where the audio logs are stored
   + Optional. To encrypt audio logs with a specific AWS KMS key, set the `kmsKeyArn` member of the ARN of the key that is used for encryption.

1. Set the `iamRoleArn` member of the `conversationLogs` field to the Amazon Resource Name (ARN) of an IAM role that has the required permissions for enabling conversation logs on the specified resources.

## Disabling Conversation Logs


**To turn off logs using the console**

1. Open the Amazon Lex console [https://console.aws.amazon.com/lex](https://console.aws.amazon.com/lex).

1. From the list, choose a bot.

1. Choose the **Settings** tab, and then from the left menu choose **Conversation logs**.

1. In the list of aliases, choose the settings icon for the alias for which you want to configure conversation logs.

1. Clear the check from text, audio, or both to turn off logging.

1. Choose **Save** to stop logging conversations.

**To turn off logs using the API**
+ Call the `PutBotAlias` operation without the `conversationLogs` field.

**To turn off text logs using the API**
+ 
  + If you are logging audio
    + Call the [PutBotAlias](API_PutBotAlias.md) operation with a `logSettings` entry only for `AUDIO`.
    + The call to the `PutBotAlias` operation must not have a `logSettings` entry for `TEXT`.
  + If you are not logging audio
    + Call the [PutBotAlias](API_PutBotAlias.md) operation without the `conversationLogs` field.

**To turn off audio logs using the API**
+ 
  + If you are logging text
    + Call the [PutBotAlias](API_PutBotAlias.md) operation with a `logSettings` entry only for `TEXT`.
    + The call to the `PutBotAlias` operation must not have a `logSettings` entry for `AUDIO`.
  + If you are not logging text
    + Call the [PutBotAlias](API_PutBotAlias.md) operation without the `conversationLogs` field.

# Encrypting Conversation Logs


You can use encryption to help protect the contents of your conversation logs. For text and audio logs, you can use AWS KMS customer managed CMKs to encrypt data in your CloudWatch Logs log group and S3 bucket.

**Note**  
Amazon Lex supports only symmetric CMKs. Do not use an asymmetric CMK to encrypt your data.

You enable encryption using an AWS KMS key on the CloudWatch Logs log group that Amazon Lex uses for text logs. You can't provide an AWS KMS key in the log settings to enable AWS KMS encryption of your log group. For more information, see [ Encrypt Log Data in CloudWatch Logs Using AWS KMS](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html) in the *Amazon CloudWatch Logs User Guide*.

For audio logs you use default encryption on your S3 bucket or specify an AWS KMS key to encrypt your audio objects. Even if your S3 bucket uses default encryption you can still specify a different AWS KMS key to encrypt your audio objects. For more information, see [ Amazon S3 Default Encryption for S3 Buckets ](https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html) in the *Amazon Simple Storage Service Developer Guide*.

Amazon Lex requires AWS KMS permissions if you choose to encrypt your audio logs. You need to attach additional policies to the IAM role used for conversation logs. If you use default encryption on your S3 bucket, your policy must grant access to the AWS KMS key configured for that bucket. If you specify an AWS KMS key in your audio log settings, your must grant access to that key.

If you have not created a role for conversation logs, see [IAM Policies for Conversation Logs](conversation-logs-policies.md).

**To create an IAM policy for using an AWS KMS key for encrypting audio logs**

1. Create a document in the current directory called **LexConversationLogsKMSPolicy.json**, add the following policy to it, and save it.

1. In the AWS CLI, create the IAM policy that grants permission to use the AWS KMS key for encrypting audio logs.

   ```
   aws iam create-policy \
       --policy-name kms-policy-name \
       --policy-document file://LexConversationLogsKMSPolicy.json
   ```

1. Attach the policy to the role that you created for conversation logs.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::account-id:policy/kms-policy-name \
       --role-name role-name
   ```

# Viewing Text Logs in Amazon CloudWatch Logs


Amazon Lex stores text logs for your conversations in Amazon CloudWatch Logs. To view the logs, you can use the CloudWatch Logs console or API. For more information, see [ Search Log Data Using Filter Patterns ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SearchDataFilterPattern.html) and [CloudWatch Logs Insights Query Syntax](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html) in the *Amazon CloudWatch Logs User Guide*.

**To view logs using the Amazon Lex console**

1. Open the Amazon Lex console [https://console.aws.amazon.com/lex](https://console.aws.amazon.com/lex).

1. From the list, choose a bot.

1. Choose the **Settings** tab, then from the left menu choose **Conversation logs**.

1. Choose the link under **Text logs** to view the logs for the alias in the CloudWatch console.

You can also use the CloudWatch console or API to view your log entries. To find the log entries, navigate to the log group that you configured for the alias. You find the log stream prefix for your logs in the Amazon Lex console or by using the [GetBotAlias](API_GetBotAlias.md) operation. 

Log entries for a user utterance is in multiple log streams. An utterance in the conversation has an entry in one of the log streams with the specified prefix. An entry in the log stream contains the following information.

```
{
   "messageVersion": "1.0",
   "botName": "bot name",
   "botAlias": "bot alias",
   "botVersion": "bot version",
   "inputTranscript": "text used to process the request",
   "botResponse": "response from the bot",
   "intent": "matched intent",
   "nluIntentConfidence": "number",
   "slots": {
       "slot name": "slot value",
       "slot name": null,
       "slot name": "slot value"
       ...
   },
   "alternativeIntents": [
       {
           "name": "intent name",
           "nluIntentConfidence": "number",
           "slots": {
               "slot name": slot value,
               "slot name": null,
               "slot name": slot value
               ...
           }
       },
       {
           "name": "intent name",
           "nluIntentConfidence": number,
           "slots": {}
       }
   ],
   "developerOverride": "true" | "false",
   "missedUtterance": true | false,
   "inputDialogMode": "Text" | "Speech",
   "requestId": "request ID",
   "s3PathForAudio": "S3 path to audio file",
   "userId": "user ID",
   "sessionId": "session ID",
   "sentimentResponse": {
       "sentimentScore": "{Positive: number, Negative: number, Neutral: number, Mixed: number}",
       "sentimentLabel": "Positive" | "Negative" | "Neutral" | "Mixed"
   },
   "slotToElicit": "slot name",
   "dialogState": "ElicitIntent" | "ConfirmIntent" | "ElicitSlot" | "Fulfilled" | "ReadyForFulfillment" | "Failed",
   "responseCard": {
       "genericAttachments": [
           ...
       ],
       "contentType": "application/vnd.amazonaws.card.generic",
       "version": 1
    },
   "locale": "locale",
   "timestamp": "ISO 8601 UTC timestamp",
   "kendraResponse": {
      "totalNumberOfResults": number,
      "resultItems": [
          {
              "id": "query ID",
              "type": "DOCUMENT" | "QUESTION_ANSWER" | "ANSWER",
              "additionalAttributes": [
                  {
                     ...
                  }
              ],
              "documentId": "document ID",
              "documentTitle": {
                  "text": "title",
                  "highlights": null
              },
              "documentExcerpt": {
                  "text": "text",
                  "highlights": [
                      {
                          "beginOffset": number,
                          "endOffset": number,
                          "topAnswer": true | false
                      }
                  ]
              },
              "documentURI": "URI",
              "documentAttributes": []
          }  
      ],
      "facetResults": [],
      "sdkResponseMetadata": {
          "requestId": "request ID"
      },
      "sdkHttpMetadata": {
          "httpHeaders": {
              "Content-Length": "number",
              "Content-Type": "application/x-amz-json-1.1",
              "Date": "date and time",
              "x-amzn-RequestId": "request ID"
          },
          "httpStatusCode": 200
      },
      "queryId": "query ID"
   },
   "sessionAttributes": {
       "attribute name": "attribute value"
       ...
    },
   "requestAttributes": {
       "attribute name": "attribute value"
       ...
    }
}
```

The contents of the log entry depends on the result of a transaction and the configuration of the bot and request.
+ The `intent`, `slots`, and `slotToElicit` fields don't appear in an entry if the `missedUtterance` field is `true`.
+ The `s3PathForAudio` field doesn't appear if audio logs are disabled or if the `inputDialogMode`field is `Text`.
+ The `responseCard` field only appears when you have defined a response card for the bot.
+ The `requestAttributes` map only appears if you have specified request attributes in the request.
+ The `kendraResponse` field is only present when the `AMAZON.KendraSearchIntent` makes a request to search an Amazon Kendra index.
+ The `developerOverride` field is true when an alternative intent was specified in the bot's Lambda function.
+ The `sessionAttributes` map only appears if you have specified session attributes in the request.
+ The `sentimentResponse` map only appears if you configure the bot to return sentiment values.

**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.

You must have a role and policy set to enable Amazon Lex to write to CloudWatch Logs. For more information see [IAM Policies for Conversation Logs](conversation-logs-policies.md).

# Accessing Audio Logs in Amazon S3


Amazon Lex stores audio logs for your conversations in an S3 bucket. 

**To access audio logs using the console**

1. Open the Amazon Lex console [https://console.aws.amazon.com/lex](https://console.aws.amazon.com/lex).

1. From the list, choose a bot.

1. Choose the **Settings** tab, then from the left menu choose **Conversation logs**.

1. Choose the link under **Audio logs** to access the logs for the alias in the Amazon S3 console.

You can also use the Amazon S3 console or API to access audio logs. You can see the S3 object key prefix of the audio files in the Amazon Lex console, or in the `resourcePrefix` field in the `GetBotAlias` operation response.

# Monitoring Conversation Log Status with CloudWatch Metrics


Use Amazon CloudWatch to monitor delivery metrics of your conversation logs. You can set alarms on metrics so that you are aware of issues with logging if they should occur.

Amazon Lex provides four metrics in the `AWS/Lex` namespace for conversation logs:
+ `ConversationLogsAudioDeliverySuccess`
+ `ConversationLogsAudioDeliveryFailure`
+ `ConversationLogsTextDeliverySuccess`
+ `ConversationLogsTextDeliveryFailure`

For more information, see [CloudWatch Metrics for Conversation Logs](monitoring-aws-lex-cloudwatch.md#cloudwatch-metrics-for-logging).

The success metrics show that Amazon Lex has successfully written your audio or text logs to their destinations. 

The failure metrics show that Amazon Lex couldn't deliver audio or text logs to the specified destination. Typically, this is a configuration error. When your failure metrics are above zero, check the following:
+ Make sure that Amazon Lex is a trusted entity for the IAM role.
+ For text logging, make sure that the CloudWatch Logs log group exists. For audio logging, make sure that the S3 bucket exists.
+ Make sure that the IAM role that Amazon Lex uses to access the CloudWatch Logs log group or S3 bucket has write permission for the log group or bucket.
+ Make sure that the S3 bucket exists in the same region as the Amazon Lex bot and belongs to your account.
+ If you are using an AWS KMS key for S3 encryption, make sure that there are no policies that prevent Amazon Lex from using your key and make sure that the IAM role you provide has the necessary AWS KMS permissions. For more information, see [IAM Policies for Conversation Logs](conversation-logs-policies.md).

# Managing Sessions With the Amazon Lex API
Managing Sessions

When a user starts a conversation with your bot, Amazon Lex creates a *session*. The information exchanged between your application and Amazon Lex makes up the session state for the conversation. When you make a request, the session is identified by a combination of the bot name and a user identifier that you specify. For more information about the user identifier, see the `userId` field in the [PostContent](API_runtime_PostContent.md) or [PostText](API_runtime_PostText.md) operation.

The response from a session operation includes a unique session identifier that identifies a specific session with a user. You can use this identifier during testing or to help troubleshoot your bot.

You can modify the session state sent between your application and your bot. For example, you can create and modify session attributes that contain custom information about the session, and you can change the flow of the conversation by setting the dialog context to interpret the next utterance.

There are two ways that you can update session state. The first is to use a Lambda function with the `PostContent` or `PostText` operation that is called after each turn of the conversation. For more information, see [Using Lambda Functions](using-lambda.md). The other is to use the Amazon Lex runtime API in your application to make changes to the session state. 

The Amazon Lex runtime API provides operations that enable you to manage session information for a conversation with your bot. The operations are the [PutSession](API_runtime_PutSession.md) operation, the [GetSession](API_runtime_GetSession.md) operation, and the [DeleteSession](API_runtime_DeleteSession.md) operation. You use these operations to get information about the state of your user's session with your bot, and to have fine-grained control over the state.

Use the `GetSession` operation when you want to get the current state of the session. The operation returns the current state of the session, including the state of the dialog with your user, any session attributes that have been set and slot values for the last three intents that the user interacted with. 

The `PutSession` operation enables you to directly manipulate the current session state. You can set the type of dialog action that the bot will perform next. This gives you control over the flow of the conversation with the bot. Set the dialog action `type` field to `Delegate` to have Amazon Lex determine the next action for the bot.

You can use the `PutSession` operation to create a new session with a bot and set the intent that the bot should start with. You can also use the `PutSession` operation to change from one intent to another. When you create a session or change the intent you also can set session state, such as slot values and session attributes. When the new intent is finished, you have the option of restarting the prior intent. You can use the `GetSession` operation to get the dialog state of the prior intent from Amazon Lex and use the information to set the dialog state of the intent.

The response from the `PutSession` operation contains the same information as the `PostContent` operation. You can use this information to prompt the user for the next piece of information, just as you would with the response from the `PostContent` operation.

Use the `DeleteSession` operation to remove an existing session and start over with a new session. For example, when you are testing your bot you can use the `DeleteSession` operation to remove test sessions from your bot.

The session operations work with your fulfillment Lambda functions. For example, if your Lambda function returns `Failed` as the fulfillment state you can use the `PutSession` operation to set the dialog action type to `close` and `fulfillmentState` to `ReadyForFulfillment` to retry the fulfillment step.

Here are some things that you can do with the session operations:
+ Have the bot start a conversation instead of waiting for the user.
+ Switch intents during a conversation.
+ Return to a previous intent.
+ Start or restart a conversation in the middle of the interaction.
+ Validate slot values and have the bot re-prompt for values that are not valid.

Each of these are described further below.

## Switching Intents


You can use the `PutSession` operation to switch from one intent to another. You can also use it to switch back to a previous intent. You can use the `PutSession` operation to set session attributes or slot values for the new intent.
+ Call the `PutSession` operation. Set the intent name to the name of the new intent and set the dialog action to `Delegate`. You can also set any slot values or session attributes required for the new intent.
+ Amazon Lex will start a conversation with the user using the new intent.

## Resuming a Prior Intent


To resume a prior intent you use the `GetSession` operation to get the summary of the intent, and then use the `PutSession` operation to set the intent to its previous dialog state.
+ Call the `GetSession` operation. The response from the operation includes a summary of the dialog state of the last three intents that the user interacted with.
+ Using the information from the intent summary, call the `PutSession` operation. This will return the user to the previous intent in the same place in the conversation.

In some cases it may be necessary to resume your user's conversation with your bot. For example, say that you have created a customer service bot. Your application determines that the user needs to talk to a customer service representative. After talking to the user, the representative can direct the conversation back to the bot with the information that they collected.

To resume a session, use steps similar to these:
+ Your application determines that the user needs to speak to a customer service representative.
+ Use the `GetSession` operation to get the current dialog state of the intent. 
+ The customer service representative talks to the user and resolves the issue.
+ Use the `PutSession` operation to set the dialog state of the intent. This may include setting slot values, setting session attributes, or changing the intent.
+ The bot resumes the conversation with the user.

You can use the `PutSession` operation `checkpointLabel` parameter to label an intent so that you can find it later. For example, a bot that asks a customer for information might go into a `Waiting` intent while the customer gathers the information. The bot creates a checkpoint label for the current intent and then starts the `Waiting` intent. When the customer returns the bot can find the previous intent using the checkpoint label and switch back. 

The intent must be present in the `recentIntentSummaryView` structure returned by the `GetSession` operation. If you specify a checkpoint label in the `GetSession` operation request, it will return a maximum of three intents with that checkpoint label.
+ Use the `GetSession` operation to get the current state of the session.
+ Use the `PutSession` operation to add a checkpoint label to the last intent. If necessary you can use this `PutSession` call to switch to a different intent.
+ When it is time to switch back to the labeled intent, call the `GetSession` operation to return a recent intent list. You can use the `checkpointLabelFilter` parameter so that Amazon Lex returns only intents with the specified checkpoint label.

## Starting a New Session


If you want to have the bot start the conversation with your user, you can use the `PutSession` operation. 
+ Create a welcome intent with no slots and a conclusion message that prompts the user to state an intent. For example, "What would you like to order? You can say 'Order a drink' or 'Order a pizza.'"
+ Call the `PutSession` operation. Set the intent name to the name of your welcome intent and set the dialog action to `Delegate`. 
+ Amazon Lex will respond with the prompt from your welcome intent to start the conversation with your user.

## Validating Slot Values


You can validate responses to your bot using your client application. If the response isn't valid, you can use the `PutSession` operation to get a new response from your user. For example, suppose that your flower ordering bot can only sell tulips, roses, and lilies. If the user orders carnations, your application can do the following:
+ Examine the slot value returned from the `PostText` or `PostContent` response.
+ If the slot value is not valid, call the `PutSession` operation. Your application should clear the slot value, set the `slotToElicit` field, and set the `dialogAction.type` value to `elicitSlot`. Optionally, you can set the `message` and `messageFormat` fields if you want to change the message that Amazon Lex uses to elicit the slot value.

# Bot Deployment Options
Deployment Options

Currently, Amazon Lex provides the following bot deployment options:
+ [AWS Mobile SDK](https://aws.amazon.com/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](examples.md).

# Built-in Intents and Slot Types


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

**Topics**
+ [

# Built-in Intents
](howitworks-builtins-intents.md)
+ [

# Built-in Slot Types
](howitworks-builtins-slots.md)

# Built-in Intents


For common actions, you can use the 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 the base intent, such as the sample utterances. 

In the current implementation, you can't do the following: 
+ Add or remove sample utterances from the base intent
+ Configure slots for built-in intents

**To add a built-in intent to a bot**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose the bot to add the built-in intent to.

1. In the navigation pane, choose the plus (\$1) next to **Intents**.

1. For **Add intent**, choose **Search existing intents**.

1. In the **Search intents** box, type the name of the built-in intent to add to your bot.

1. For **Copy built-in intent**, give the intent a name, and then choose **Add**.

1. Configure the intent as required for your bot.

**Topics**
+ [

# AMAZON.CancelIntent
](built-in-intent-cancel.md)
+ [

# AMAZON.FallbackIntent
](built-in-intent-fallback.md)
+ [

# AMAZON.HelpIntent
](built-in-intent-help.md)
+ [

# AMAZON.KendraSearchIntent
](built-in-intent-kendra-search.md)
+ [

# AMAZON.PauseIntent
](built-in-intent-pause.md)
+ [

# AMAZON.RepeatIntent
](built-in-intent-repeat.md)
+ [

# AMAZON.ResumeIntent
](built-in-intent-resume.md)
+ [

# AMAZON.StartOverIntent
](built-in-intent-start-over.md)
+ [

# AMAZON.StopIntent
](built-in-intent-stop.md)

**Note**  
For the English (US) (en-US) locale, Amazon Lex supports intents from the Alexa standard built-in intents. For a list of built-in intents, see [Standard Built-in Intents](https://developer.amazon.com/docs/custom-skills/standard-built-in-intents.html) in the *Alexa Skills Kit*.  
Amazon Lex doesn't support the following intents:  
`AMAZON.YesIntent`
`AMAZON.NoIntent` 
The intents in the [Built-in Intent Library](https://developer.amazon.com/docs/custom-skills/built-in-intent-library.html) in the *Alexa Skills Kit*

# AMAZON.CancelIntent


Responds to words and phrases that indicate the user wants to cancel the current interaction. Your application can use this intent to remove slot type values and other attributes before ending the interaction with the user.

Common utterances:
+ cancel
+ never mind
+ forget it

# AMAZON.FallbackIntent


When a user's input to an intent isn't what a bot expects, you can configure Amazon Lex to invoke a *fallback intent*. For example, if the user input "I'd like to order candy" doesn't match an intent in your `OrderFlowers` bot, Amazon Lex invokes the fallback intent to handle the response.

You add a fallback intent by adding the built-in `AMAZON.FallbackIntent` intent type to your bot. You can specify the intent using the [PutBot](API_PutBot.md) operation or by choosing the intent from the list of built-in intents in the console. 

Invoking a fallback intent uses two steps. In the first step the fallback intent is matched based on the input from the user. When the fallback intent is matched, the way the bot behaves depends on the number of retries configured for a prompt. For example, if the maximum number of attempts to determine an intent is 2, the bot returns the bot's clarification prompt twice before invoking the fallback intent.

Amazon Lex matches the fallback intent in these situations: 
+ The user's input to an intent doesn't match the input that the bot expects
+ Audio input is noise, or text input isn't recognized as words.
+ The user's input is ambiguous and Amazon Lex can't determine which intent to invoke.

The fallback intent is invoked when:
+ The bot doesn't recognize the user input as an intent after the configured number of tries for clarification when the conversation is started.
+ An intent doesn't recognize the user input as a slot value after the configured number of tries.
+ An intent doesn't recognize the user input as a response to a confirmation prompt after the configured number of tries.

You can use the following with a fallback intent:
+ A fulfillment Lambda function
+ A conclusion statement
+ A follow up prompt

You can't add the following to a fallback intent:
+ Utterances
+ Slots
+ An initialization and validation Lambda function 
+ A confirmation prompt

If you have configured both a cancel statement and a fallback intent for a bot, Amazon Lex uses the fallback intent. If you need your bot to have a cancel statement, you can use the fulfillment function for the fallback intent to provide the same behavior as a cancel statement. For more information, see the `abortStatement` parameter of the [PutBot](API_PutBot.md) operation.

## Using Clarification Prompts


If you provide your bot with a clarification prompt, the prompt is used to solicit a valid intent from the user. The clarification prompt will be repeated the number of times that you configured. After that the fallback intent will be invoked.

If you don't set a clarification prompt when you create a bot and the user doesn't start the conversation with a valid intent, Amazon Lex immediately calls your fallback intent . 

When you use a fallback intent without a clarification prompt, Amazon Lex doesn't call the fallback under these circumstances:
+ When the user responds to a follow-up prompt but doesn't provide an intent. For example, in response to a follow-up prompt that says "Would you like anything else today?", the user says "Yes." Amazon Lex returns a 400 Bad Request exception because it doesn't have a clarification prompt to send to the user to get an intent.
+ When using an AWS Lambda function, you return an `ElicitIntent` dialog type. Because Amazon Lex doesn't have a clarification prompt to get an intent from the user, it returns a 400 Bad Request exception.
+ When using the `PutSession` operation, you send an `ElicitIntent` dialog type. Because Amazon Lex doesn't have a clarification prompt to get an intent from the user, it returns a 400 Bad Request exception.

## Using a Lambda Function with a Fallback Intent


When a fallback intent is invoked, the response depends on the setting of the `fulfillmentActivity` parameter to the [PutIntent](API_PutIntent.md) operation. The bot does one of the following:
+ Returns the intent information to the client application.
+ Calls the fulfillment Lambda function. It calls the function with the session variables that are set for the session.

For more information about setting the response when a fallback intent is invoked, see the `fulfillmentActivity` parameter of the [PutIntent](API_PutIntent.md) operation. 

If you use the fulfillment Lambda function in your fallback intent, you can use this function to call another intent or to perform some form of communication with the user, such as collecting a callback number or opening a session with a customer service representative.

You can perform any action in a fallback intent Lambda function that you can perform in the fulfillment function for any other intent. For more information about creating a fulfillment function using AWS Lambda, see [Using Lambda Functions](using-lambda.md).

A fallback intent can be invoked multiple times in the same session. For example, suppose that your Lambda function uses the `ElicitIntent` dialog action to prompt the user for a different intent. If Amazon Lex can't infer the user's intent after the configured number of tries, it invokes the fallback intent again. It also invokes the fallback intent when the user doesn't respond with a valid slot value after the configured number of tries.

You can configure a Lambda function to keep track of the number of times that the fallback intent is called using a session variable. Your Lambda function can take a different action if it is called more times than the threshold that you set in your Lambda function. For more information about session variables, see [Setting Session Attributes](context-mgmt-session-attribs.md).

# AMAZON.HelpIntent


Responds to words or phrases that indicate the user needs help while interacting with your bot. When this intent is invoked, you can configure your Lambda function or application to provide information about the your bot's capabilities, ask follow up questions about areas of help, or hand the interaction over to a human agent. 

Common utterances:
+ help
+ help me
+ can you help me

# AMAZON.KendraSearchIntent


To search documents that you have indexed with Amazon Kendra, use the `AMAZON.KendraSearchIntent` intent. When Amazon Lex can't determine the next action in a conversation with the user, it triggers the search intent.

The `AMAZON.KendraSearchIntent` is available only in the English (US) (en-US) locale and in the US East (N. Virginia), US West (Oregon) and Europe (Ireland) Regions.

Amazon Kendra is a machine-learning-based search service that indexes natural language documents such as PDF documents or Microsoft Word files. It can search indexed documents and return the following types of responses to a question:
+ An answer 
+ An entry from a FAQ that might answer the question
+ A document that is related to the question

For an example of using the `AMAZON.KendraSearchIntent`, see [Example: Creating a FAQ Bot for an Amazon Kendra Index](faq-bot-kendra-search.md).

If you configure an `AMAZON.KendraSearchIntent` intent for your bot, Amazon Lex calls the intent whenever it can't determine the user utterance for a slot or intent. For example, if your bot is eliciting a response for a slot type called "pizza topping" and the user says "What is a pizza?," Amazon Lex calls the `AMAZON.KendraSearchIntent` to handle the question. If there is no response from Amazon Kendra, the conversation continues as configured in the bot.

When you use both the `AMAZON.KendraSearchIntent` and the `AMAZON.FallbackIntent` in the same bot, Amazon Lex uses the intents as follows:

1. Amazon Lex calls the `AMAZON.KendraSearchIntent`. The intent calls the Amazon Kendra `Query` operation.

1. If Amazon Kendra returns a response, Amazon Lex displays the result to the user.

1. If there is no response from Amazon Kendra, Amazon Lex re-prompts the user. The next action depends on response from the user.
   + If the response from the user contains an utterance that Amazon Lex recognizes, such as filling a slot value or confirming an intent, the conversation with the user proceeds as configured for the bot.
   + If the response from the user does not contain an utterance that Amazon Lex recognizes, Amazon Lex makes another call to the `Query` operation.

1. If there is no response after the configured number of retries, Amazon Lex calls the `AMAZON.FallbackIntent` and ends the conversation with the user.

There are three ways to use the `AMAZON.KendraSearchIntent` to make a request to Amazon Kendra:
+ Let the search intent make the request for you. Amazon Lex calls Amazon Kendra with the user's utterance as the search string. When you create the intent, you can define a query filter string that limits the number of responses that Amazon Kendra returns. Amazon Lex uses the filter in the query request.
+ Add additional query parameters to the request to narrow the search results using your dialog Lambda function. You add a `kendraQueryFilterString` field that contains Amazon Kendra query parameters to the `delegate` dialog action. When you add query parameters to the request with the Lambda function, they take precedence over the query filter that you defined when you created the intent.
+ Create a new query using the dialog Lambda function. You can create a complete Amazon Kendra query request that Amazon Lex sends. You specify the query in the `kendraQueryRequestPayload` field in the `delegate` dialog action. The `kendraQueryRequestPayload` field takes precedence over the `kendraQueryFilterString` field.

To specify the `queryFilterString` parameter when you create a bot, or to specify the `kendraQueryFilterString` field when you call the `delegate` action in a dialog Lambda function, you specify a string that is used as the attribute filter for the Amazon Kendra query. If the string isn't a valid attribute filter, you'll get an `InvalidBotConfigException` exception at runtime. For more information about attribute filters, see [Using document attributes to filter queries](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering) in the *Amazon Kendra Developer Guide*.

To have control over the query that Amazon Lex sends to Amazon Kendra, you can specify a query in the `kendraQueryRequestPayload`field in your dialog Lambda function. If the query isn't valid, Amazon Lex returns an `InvalidLambdaResponseException` exception. For more information, see the [Query operation](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html) in the *Amazon Kendra Developer Guide*.

For an example of how to use the `AMAZON.KendraSearchIntent`, see [Example: Creating a FAQ Bot for an Amazon Kendra Index](faq-bot-kendra-search.md).

## IAM Policy for Amazon Kendra Search
IAM Policy

To use the `AMAZON.KendraSearchIntent` intent, you must use a role that provides AWS Identity and Access Management (IAM) policies that enable Amazon Lex to assume a runtime role that has permission to call the Amazon Kendra `Query` intent. The IAM settings that you use depend on whether you create the `AMAZON.KendraSearchIntent` using the Amazon Lex console, or using an AWS SDK or the AWS Command Line Interface (AWS CLI). When you use the console, you can choose between adding permission to call Amazon Kendra to the Amazon Lex service-linked role or using a role specifically for calling the Amazon Kendra `Query` operation. When you use the AWS CLI or an SDK to create the intent, you must use a role specifically for calling the `Query` operation.

### Attaching Permissions


You can use the console to attach permissions to access the Amazon Kendra `Query` operation to the default Amazon Lex service-linked role. When you attach permissions to the service-linked role, you don't have to create and manage a runtime role specifically to connect to the Amazon Kendra index.

The user, role, or group that you use to access the Amazon Lex console must have permissions to manage role policies. Attach the following IAM policy to the console access role. When you grant these permissions, the role has permissions to change the existing service-linked role policy. 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:PutRolePolicy",
                "iam:GetRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots"
        },
        {
            "Effect": "Allow",
            "Action": "iam:ListRoles",
            "Resource": "*"
        }
    ]
}
```

------

### Specifying a Role


You can use the console, the AWS CLI, or the API to specify a runtime role to use when calling the Amazon Kendra `Query` operation. 

The user, role, or group that you use to specify the runtime role must have the `iam:PassRole` permission. The following policy defines the permission. You can use the `iam:AssociatedResourceArn` and `iam:PassedToService` condition context keys to further limit the scope of the permissions. For more information, see [ IAM and AWS STS Condition Context Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html) in the *AWS Identity and Access Management User Guide*.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/role"
        }
    ]
}
```

------

The runtime role that Amazon Lex needs to use to call Amazon Kendra must have the `kendra:Query` permissions. When you use an existing IAM role for permission to call the Amazon Kendra `Query` operation, the role must have the following policy attached.

You can use the IAM console, the IAM API, or the AWS CLI to create a policy and attach it to a role. These instructions use the AWS CLI to create the role and policies.

**Note**  
The following code is formatted for Linux and MacOS. For Windows, replace the Linux line continuation character (\$1) with a caret (^).

**To add Query operation permission to a role**

1. Create a document called **KendraQueryPolicy.json** in the current directory, add the following code to it, and save it

1. In the AWS CLI, run the following command to create the IAM policy for running the Amazon Kendra `Query` operation.

   ```
   aws iam create-policy \
       --policy-name query-policy-name \
       --policy-document file://KendraQueryPolicy.json
   ```

1. Attach the policy to the IAM role that you are using to call the `Query` operation.

   ```
   aws iam attach-role-policy \
       --policy-arn arn:aws:iam::account-id:policy/query-policy-name
       --role-name role-name
   ```

You can choose to update the Amazon Lex service-linked role or to use a role that you created when you create the `AMAZON.KendraSearchIntent` for your bot. The following procedure shows how to choose the IAM role to use.

**To specify the runtime role for AMAZON.KendraSearchIntent**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose the bot that you want to add the `AMAZON.KendraSearchIntent` to.

1. Choose the plus (\$1) next to **Intents**.

1. In **Add intent**, choose **Search existing intents**.

1. In **Search intents**, enter **AMAZON.KendraSearchIntent** and then choose **Add**.

1. In **Copy built-in intent**, enter a name for the intent, such as **KendraSearchIntent**, and then choose **Add**.

1. Open the **Amazon Kendra query** section.

1. For **IAM role** choose one of the following options:
   + To update the Amazon Lex service-linked role to enable your bot to query Amazon Kendra indexes, choose **Add Amazon Kendra permissions**.
   + To use a role that has permission to call the Amazon Kendra `Query` operation, choose **Use an existing role**.

## Using Request and Session Attributes as Filters


To filter the response from Amazon Kendra to items related to current conversation, use session and request attributes as filters by adding the `queryFilterString` parameter when you create your bot. You specify a placeholder for the attribute when you create the intent, and then Amazon Lex V2 substitutes a value before it calls Amazon Kendra. For more information about request attributes, see [Setting Request Attributes](context-mgmt-request-attribs.md). For more information about session attributes, see [Setting Session Attributes](context-mgmt-session-attribs.md).

The following is a example of a `queryFilterString` parameter that uses a string to filter the Amazon Kendra query.

```
"{"equalsTo": {"key": "City", "value": {"stringValue": "Seattle"}}}"
```

The following is an example of a `queryFilterString` parameter that uses a session attribute called `"SourceURI"` to filter the Amazon Kendra query.

```
"{"equalsTo": {"key": "SourceURI","value": {"stringValue": "[FileURL]"}}}"
```

The following is an example of a `queryFilterString` parameter that uses a request attribute called `"DepartmentName"` to filter the Amazon Kendra query.

```
"{"equalsTo": {"key": "Department","value": {"stringValue": "((DepartmentName))"}}}"
```

The `AMAZON.KendraSearchInteng` filters use the same format as the Amazon Kendra search filters. For more information, see [Using document attributes to filter search results](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering) in the *Amazon Kendra developer guide*.

The query filter string used with the `AMAZON.KendraSearchIntent` must use lower-case letters for the first letter of each filter. For example, the following is a valid query filter for the `AMAZON.KendraSearchIntent`.

```
{
    "andAllFilters": [
        {
            "equalsTo": {
                "key": "City",
                "value": {
                    "stringValue": "Seattle"
                }
            }
        },
        {
            "equalsTo": {
                "key": "State",
                "value": {
                    "stringValue": "Washington"
                }
            }
        }
    ]
}
```

## Using the Search Response


Amazon Kendra returns the response to a search in the intent's `conclusion` statement. The intent must have a `conclusion` statement unless a fulfillment Lambda function produces a conclusion message.

Amazon Kendra has four types of responses. 
+ `x-amz-lex:kendra-search-response-question_answer-question-<N>` – The question from a FAQ that matches the search.
+ `x-amz-lex:kendra-search-response-question_answer-answer-<N>` – The answer from a FAQ that matches the search.
+ `x-amz-lex:kendra-search-response-document-<N>` – An excerpt from a document in the index that is related to the text of the utterance.
+ `x-amz-lex:kendra-search-response-document-link-<N>` – The URL of a document in the index that is related to the text of the utterance.
+ `x-amz-lex:kendra-search-response-answer-<N>` – An excerpt from a document in the index that answers the question.

The responses are returned in `request` attributes. There can be up to five responses for each attribute, numbered 1 through 5. For more information about responses, see [Types of response](https://docs.aws.amazon.com/kendra/latest/dg/response-types.html) in the *Amazon Kendra Developer Guide*. 

The `conclusion` statement must have one or more message groups. Each message group contains one or more messages. Each message can contain one or more placeholder variables that are replaced by request attributes in the response from Amazon Kendra. There must be at least one message in the message group where all of the variables in the message are replaced by request attribute values in the runtime response, or there must be a message in the group with no placeholder variables. The request attributes are set off with double parentheses ("((" "))"). The following message group messages match any response from Amazon Kendra:
+ “I found a FAQ question for you: ((x-amz-lex:kendra-search-response-question\$1answer-question-1)), and the answer is ((x-amz-lex:kendra-search-response-question\$1answer-answer-1))”
+ “I found an excerpt from a helpful document: ((x-amz-lex:kendra-search-response-document-1))”
+ “I think the answer to your questions is ((x-amz-lex:kendra-search-response-answer-1))”

## Using a Lambda Function to Manage the Request and Response


The `AMAZON.KendraSearchIntent` intent can use your dialog code hook and fulfillment code hook to manage the request to Amazon Kendra and the response. Use the dialog code hook Lambda function when you want to modify the query that you send to Amazon Kendra, and the fulfillment code hook Lambda function when you want to modify the response.

### Creating a Query with the Dialog Code Hook


You can use the dialog code hook to create a query to send to Amazon Kendra. Using the dialog code hook is optional. If you don't specify a dialog code hook, Amazon Lex constructs a query from the user utterance and uses the `queryFilterString` that you provided when you configured the intent, if you provided one.

You can use two fields in the dialog code hook response to modify the request to Amazon Kendra:
+ `kendraQueryFilterString` – Use this string to specify attribute filters for the Amazon Kendra request. You can filter the query using any of the index fields defined in your index. For the structure of the filter string, see [Using document attributes to filter queries](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering) in the *Amazon Kendra Developer Guide*. If the specified filter string isn't valid, you will get an `InvalidLambdaResponseException` exception. The `kendraQueryFilterString` string overrides any query string specified in the `queryFilterString` configured for the intent.
+ `kendraQueryRequestPayload` – Use this string to specify an Amazon Kendra query. Your query can use any of the features of Amazon Kendra. If you don't specify a valid query, you get a `InvalidLambdaResponseException` exception. For more information, see [Query](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html) in the *Amazon Kendra Developer Guide*.

After you have created the filter or query string, you send the response to Amazon Lex with the `dialogAction` field of the response set to `delegate`. Amazon Lex sends the query to Amazon Kendra and then returns the query response to the fulfillment code hook.

### Using the Fulfillment Code Hook for the Response


After Amazon Lex sends a query to Amazon Kendra, the query response is returned to the `AMAZON.KendraSearchIntent` fulfillment Lambda function. The input event to the code hook contains the complete response from Amazon Kendra. The query data is in the same structure as the one returned by the Amazon Kendra `Query` operation. For more information, see [ Query response syntax](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax) in the *Amazon Kendra Developer Guide*.

The fulfillment code hook is optional. If one does not exist, or if the code hook doesn't return a message in the response, Amazon Lex uses the `conclusion` statement for responses.

# Example: Creating a FAQ Bot for an Amazon Kendra Index


This example creates an Amazon Lex bot that uses an Amazon Kendra index to provide answers to users' questions. The FAQ bot manages the dialog for the user. It uses the `AMAZON.KendraSearchIntent` intent to query the index and to present the response to the user. To create the bot, you: 

1. Create a bot that your customers will interact with to get answers from your bot.

1. Create a custom intent. Your bot requires at least one intent with at least one utterance. This intent enables your bot to build, but is not used otherwise.

1. Add the `KendraSearchIntent` intent to your bot and configure it to work with your Amazon Kendra index.

1. Test the bot by asking questions that are answered by documents stored in your Amazon Kendra index.

Before you can use this example, you need to create an Amazon Kendra index. For more information, see [Getting started with an S3 bucket (console) ](https://docs.aws.amazon.com/kendra/latest/dg/gs-console.html) in the *Amazon Kendra Developer Guide*.

**To create a FAQ bot**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. In the navigation pane, choose **Bots**. 

1. Choose **Create**.

1. Choose **Custom bot**. Configure the bot as follows:
   + **Bot name** – Give the bot a name that indicates its purpose, such as **KendraTestBot**.
   + **Output voice** – Choose **None**.
   + **Session timeout** – Enter **5**.
   + **Sentiment analysis** – Choose **No**.
   + **COPPA** – Choose **No**.
   + **User utterance storage** – Choose **Do not store**.

1. Choose **Create**.

To successfully build a bot, you must create at least one intent with at least one sample utterance. This intent is required to build your Amazon Lex bot, but isn't used for the FAQ response. The utterance for the intent must not apply to any of the questions that your customer asks.

**To create the required intent**

1. On the **Getting started with your bot** page, choose **Create intent**.

1. For **Add intent**, choose **Create intent**.

1. In the **Create intent** dialog box, give the intent a name, such as **RequiredIntent**.

1. For **Sample utterances**, type an utterance, such as **Required utterance**.

1. Choose **Save intent**.

Now, create the intent to search an Amazon Kendra index and the response messages that it should return.

**To create an AMAZON.KendraSearchIntent intent and response message**

1. In the navigation pane, choose the plus (\$1) next to **Intents**.

1. For **Add intent**, choose **Search existing intents**.

1. In the **Search intents** box, enter **AMAZON.KendraSearchIntent**, then choose it from the list.

1. For **Copy built-in intent**, give the intent a name, such as **KendraSearchIntent**, and then choose **Add**. 

1. In the intent editor, choose **Amazon Kendra query** to open the query options.

1. From the **Amazon Kendra index** menu, choose the index that you want the intent to search.

1. In the **Response** section, add the following three messages:

   ```
   I found a FAQ question for you: ((x-amz-lex:kendra-search-response-question_answer-question-1)) and the answer is ((x-amz-lex:kendra-search-response-question_answer-answer-1)).
   I found an excerpt from a helpful document: ((x-amz-lex:kendra-search-response-document-1)).
   I think the answer to your questions is ((x-amz-lex:kendra-search-response-answer-1)).
   ```

1. Choose **Save intent**, and then choose **Build** to build the bot.

Finally, use the console test window to test responses from your bot. Your questions should be in the domain that your index supports.

**To test your FAQ bot**

1. In the console test window, type a question for your index.

1. Verify the answer in the test window's response section.

1. To reset the test window for another question, choose **Clear chat history**.

# AMAZON.PauseIntent


Responds to words and phrases that enable the user to pause an interaction with a bot so that they can return to it later. Your Lambda function or application needs to save intent data in session variables, or you need to use the [GetSession](API_runtime_GetSession.md) operation to retrieve intent data when you resume the current intent.

Common utterances:
+ pause
+ pause that

# AMAZON.RepeatIntent


Responds to words and phrases that enable the user to repeat the previous message. Your application needs to use a Lambda function to save the previous intent information in session variables, or you need to use the [GetSession](API_runtime_GetSession.md) operation to get the previous intent information.

Common utterances:
+ repeat
+ say that again
+ repeat that

# AMAZON.ResumeIntent


Responds to words and phrases the enable the user to resume a previously paused intent. You Lambda function or application must manage the information required to resume the previous intent.

Common utterances:
+ resume
+ continue
+ keep going

# AMAZON.StartOverIntent


Responds to words and phrases that enable the user to stop processing the current intent and start over from the beginning. You can use your Lambda function or the `PutSession` operation to elicit the first slot value again.

Common utterances:
+ start over
+ restart
+ start again

# AMAZON.StopIntent


Responds to words and phrases that indicate that the user wants to stop processing the current intent and end the interaction with a bot. Your Lambda function or application should clear any existing attributes and slot type values and then end the interaction.

Common utterances:
+ stop
+ off
+ shut up

# Built-in Slot Types


Amazon Lex supports built-in slot types that define how data in the slot is recognized and handled. 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. 


| Slot Type | Short Description | Supported Locales | 
| --- | --- | --- | 
| [AMAZON.Airport](built-in-slot-airport.md) | Recognizes words that represent an airport. | All locales | 
| [AMAZON.AlphaNumeric](built-in-slot-alphanumeric.md) | Recognizes words made up of letters and numbers. | All locales except Korean (ko-KR) | 
| [AMAZON.City](built-in-slot-city.md) | Recognizes words that represent a city. | All locales | 
| [AMAZON.Country](built-in-slot-country.md) | Recognizes words that represent a country. | All locales | 
| [AMAZON.DATE](built-in-slot-date.md) | Recognizes words that represent a date and converts them to a standard format. | All locales | 
| [AMAZON.DURATION](built-in-slot-duration.md) | Recognizes words that represent duration and converts them to a standard format. | All locales | 
| [AMAZON.EmailAddress](built-in-slot-email.md) | Recognizes words that represent an email address and converts them into a standard email address. | All locales | 
| [AMAZON.FirstName](built-in-slot-first-name.md) | Recognizes words that represent a first name. | All locales | 
| [AMAZON.LastName](built-in-slot-last-name.md) | Recognizes words that represent a last name. | All locales | 
| [AMAZON.NUMBER](built-in-slot-number.md) | Recognizes numeric words and converts them into digits. | All locales | 
| [AMAZON.Percentage](built-in-slot-percent.md) | Recognizes words that represent a percentage and converts them to a number and a percent sign (%). | All locales | 
| [AMAZON.PhoneNumber](built-in-slot-phone.md) | Recognizes words that represent a phone number and converts them into a numeric string. | All locales | 
| [AMAZON.SpeedUnit](built-in-slot-speed.md) | Recognizes words that represent a speed unit and converts them into a standard abbreviation. | English (US) (en-US) | 
| [AMAZON.State](built-in-slot-state.md) | Recognizes words that represent a state. | All locales | 
| [AMAZON.StreetName](built-in-slot-street-name.md) | Recognizes words that represent a street name. | All locales except English (US) (en-US) | 
| [AMAZON.TIME](built-in-slot-time.md) | Recognizes words that indicate times and converts them into a time format. | All locales | 
| [AMAZON.WeightUnit](built-in-slot-weight.md) | Recognizes words that represent a weight unit and converts them into a standard abbreviation  | English (US) (en-US) | 

**Note**  
For the English (US) (en-US) locale, Amazon Lex supports slot types from the Alexa Skill Kit. For a list of available built-in slot types, see the [Slot Type Reference](https://developer.amazon.com/docs/custom-skills/slot-type-reference.html) in the Alexa Skills Kit documentation.   
Amazon Lex doesn't support the `AMAZON.LITERAL` or the `AMAZON.SearchQuery` built-in slot types. 

# AMAZON.Airport


Provides a list of airports. Examples include:
+ John F. Kennedy International Airport
+ Melbourne Airport

# AMAZON.AlphaNumeric


Recognizes strings made up of letters and numbers, such as **APQ123**.

This slot type is not available in the Korean (ko-KR) locale.

You can use the `AMAZON.AlphaNumeric` slot type for strings that contain: 
+ Alphabetical characters, such as **ABC**
+ Numeric characters, such as **123**
+ A combination of alphanumeric characters, such as **ABC123**

You can add a regular expression to the `AMAZON.AlphaNumeric` slot type to validate values entered for the slot. For example, you can use a regular expression to validate:
+ United Kingdom or Canadian postal codes
+ Driver's license numbers
+ Vehicle identification numbers

Use a standard regular expression. Amazon Lex supports the following characters in the regular expression:
+ A-Z, a-z
+ 0-9

Amazon Lex also supports Unicode characters in regular expressions. The form is `\uUnicode`. Use four digits to represent Unicode characters. For example, `[\u0041-\u005A]` is equivalent to [A-Z].

The following regular expression operators are not supported:
+ Infinite repeaters: \$1, \$1, or \$1x,\$1 with no upper bound.
+ Wild card (.)

The maximum length of the regular expression is 300 characters. The maximum length of a string stored in an AMAZON.AlphaNumeric slot type that uses a regular expression is 30 characters.

The following are some example regular expressions.
+ Alphanumeric strings, such as **APQ123** or **APQ1**: `[A-Z]{3}[0-9]{1,3}` or a more constrained `[A-DP-T]{3} [1-5]{1,3}`
+ US Postal Service Priority Mail International format, such as **CP123456789US**: `CP[0-9]{9}US`
+ Bank routing numbers, such as **123456789**: `[0-9]{9}`

To set the regular expression for a slot type, use the console or the [PutSlotType](API_PutSlotType.md) operation. The regular expression is validated when you save the slot type. If the expression isn't valid, Amazon Lex returns an error message.

When you use a regular expression in a slot type, Amazon Lex checks input to slots of that type against the regular expression. If the input matches the expression, the value is accepted for the slot. If the input does not match, Amazon Lex prompts the user to repeat the input. 

# AMAZON.City


Provides a list of local and world cities. The slot type recognizes common variations of city names. Amazon Lex doesn't convert from a variation to an official name.

Examples:
+ New York
+ Reykjavik
+ Tokyo
+ Versailles

# AMAZON.Country


The names of countries around the world. Examples:
+ Australia
+ Germany
+ Japan
+ United States
+ Uruguay

# AMAZON.DATE


Converts words that represent dates into a date format.

The date is provided to your intent in ISO-8601 date format. The date that your intent receives in the slot can vary depending on the specific phrase uttered by the user.
+ Utterances that map to a specific date, such as "today," "now," or "November twenty-fifth," convert to a complete date: `2020-11-25`. This defaults to dates *on or after* the current date.
+ Utterances that map to a specific week, such as "this week," or "next week," convert to the date of the first day of the week. In ISO-8601 format, the week starts on Monday and ends on Sunday. For example, if today is 2020-11-25, "next week" converts to `2020-11-30`.
+ Utterances that map to a month, but not a specific day, such as "next month," convert to the last day of the month. For example, if today is 2020-11-25, "next month" converts to `2020-12-31`.
+ Utterances that map to a year, but not a specific month or day, such as "next year," convert to the last day of the following year. For example, if today is 2020-11-25, "next year" converts to `2021-12-31`.

# AMAZON.DURATION


Converts words that indicate durations into a numeric duration.

The duration is resolved to a format based on the [ISO-8601 duration format](https://en.wikipedia.org/wiki/ISO_8601#Durations), `PnYnMnWnDTnHnMnS`. The `P` indicates that this is a duration, the `n` is a numeric value, and the capital letter following the `n` is the specific date or time element. For example, `P3D` means 3 days. A `T` is used to indicate that the remaining values represent time elements rather than date elements.

Examples:
+ "ten minutes": `PT10M`
+ "five hours": `PT5H`
+ "three days": `P3D`
+ "forty five seconds": `PT45S`
+ "eight weeks": `P8W`
+ "seven years": `P7Y`
+ "five hours ten minutes": `PT5H10M`
+ "two years three hours ten minutes": `P2YT3H10M`

# AMAZON.EmailAddress


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

# AMAZON.FirstName


Commonly used first names. This slot type recognizes both formal names and informal nicknames. The name sent to your intent is the value sent by the user. Amazon Lex doesn't convert from the nick name to the formal name.

For first names that sound alike but are spelled differently, Amazon Lex sends your intent a single common form.

In the English (US) (en-US) locale, use the slot name AMAZON.US\$1First\$1Name.

Examples:
+ Emily
+ John
+ Sophie

# AMAZON.LastName


Commonly used last names. For names that sound alike that are spelled differently, Amazon Lex sends your intent a single common form.

In the English (US) (en-US) locale, use the slot name AMAZON.US\$1Last\$1Name.

Examples:
+ Brosky
+ Dasher
+ Evers
+ Parres
+ Welt

# AMAZON.NUMBER


Converts 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


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.


| Input | Response | 
| --- | --- | 
| 50 percent | 50% | 
| 0.4 percent | 0.4% | 
| 23.5% | 23.5% | 
| twenty five percent | 25% | 

# AMAZON.PhoneNumber


Converts the numbers or words that represent a phone number into a string format without punctuation as follows.


| Type | Description | Input | Result | 
| --- | --- | --- | --- | 
| International number with leading plus (\$1) sign | 11-digit number with leading plus sign. | \$161 7 4445 1061 \$11 (509) 555-1212 | `+61744431061` `+15095551212` | 
| International number without leading plus (\$1) sign | 11-digit number without leading plus sign | 1 (509) 555-1212 61 7 4445 1061 | `15095551212` `61744451061` | 
| National number | 10-digit number without international code | (03) 5115 4444 (509) 555-1212 | `0351154444` `5095551212` | 
| Local number | 7-digit phone number without an international code or an area code | 555-1212 | 5551212 | 

# AMAZON.SpeedUnit


Converts words that represent speed units into the corresponding abbreviation. For example, "miles per hour" is converted to `mph`.

This slot type is available only in the English (US) (en-US) locale.

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


| Speed unit | Abbreviation | 
| --- | --- | 
|  miles per hour, mph, MPH, m/h  | mph | 
|  kilometers per hour, km per hour, kmph, KMPH, km/h  | kmph | 
|  meters per second, mps, MPS, m/s  | mps | 
| nautical miles per hour, knots, knot | knot | 

# AMAZON.State


The names of geographical and political regions within countries. 

Examples:
+ Bavaria
+ Fukushima Prefecture
+ Pacific Northwest
+ Queensland
+ Wales

# AMAZON.StreetName


The names of streets within a typical street address. This includes just the street name, not the house number.

This slot type isn't available in the English (US) (en-US) locale.

Examples:
+ Canberra Avenue
+ Front Street
+ Market Road

# AMAZON.TIME


Converts words that represent times into time values. Includes 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](lambda-input-response-format.md#using-lambda-input-event-format).

# AMAZON.WeightUnit


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

This slot type is available only in the English (US) (en-US) locale.

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](API_PutSlotType.md) 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";
   },
   "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. For example, you can have 5 slot types, each with 5,000 values and 5,000 synonyms, or you can have 10 slot types, each with 2,500 values and 2,500 synonyms. If you exceed these limits, you will get a `LimitExceededException` when you call the [PutBot](API_PutBot.md) operation.

# Slot Obfuscation


Amazon Lex enables you to obfuscate, or hide, the contents of slots so that the content is not visible. To protect sensitive data captured as slot values, you can enable slot obfuscation to mask those values in conversation logs.

When you choose to obfuscate slot values, Amazon Lex replaces the value of the slot with the name of the slot in conversation logs. For a slot called `full_name`, the value of the slot would be obfuscated as follows:

```
Before obfuscation:
    My name is John Stiles
After obfuscation:
    My name is {full_name}
```

If an utterance contains bracket characters (\$1\$1) Amazon Lex escapes the bracket characters with two back slashes (\$1\$1). For example, the text `{John Stiles}` is obfuscated as follows:

```
Before obfuscation:
    My name is {John Stiles}
After obfuscation:
    My name is \\{{full_name}\\}
```

Slot values are obfuscated in conversation logs. The slot values are still available in the response from the `PostContent` and `PostText` operations, and the slot values are available to your validation and fulfillment Lambda functions. If you are using slot values in your prompts or responses, those slot values are not obfuscated in conversation logs.

In the first turn of a conversation, Amazon Lex obfuscates slot values if it recognizes a slot and slot value in the utterance. If no slot value is recognized, Amazon Lex does not obfuscate the utterance.

On the second and later turns, Amazon Lex knows the slot to elicit and if the slot value should be obfuscated. If Amazon Lex recognizes the slot value, the value is obfuscated. If Amazon Lex does not recognize a value, the entire utterance is obfuscated. Any slot values in missed utterances won't be obfuscated.

Amazon Lex also doesn't obfuscate slot values that you store in request or session attributes. If you are storing slot values that should be obfuscated as an attribute, you must encrypt or otherwise obfuscate the value.

Amazon Lex doesn't obfuscate the slot value in audio. It does obfuscate the slot value in the audio transcription.

You don't need to obfuscate all of the slots in a bot. You can choose which slots obfuscate using the console or by using the Amazon Lex API. In the console, choose **Slot obfuscation** in the settings for a slot. If you are using the API, set the `obfuscationSetting` field of the slot to `DEFAULT_OBFUSCATION` when you call the [PutIntent](API_PutIntent.md) operation.

# Sentiment Analysis


You can use sentiment analysis to determine the sentiments expressed in a user utterance. With the sentiment information you can manage conversation flow or perform post-call analysis. For example, if the user sentiment is negative you can create a flow to hand over a conversation to a human agent.

Amazon Lex integrates with Amazon Comprehend to detect user sentiment. The response from Amazon Comprehend indicates whether the overall sentiment of the text is positive, neutral, negative, or mixed. The response contains the most likely sentiment for the user utterance and the scores for each of the sentiment categories. The score represents the likelihood that the sentiment was correctly detected.

 You enable sentiment analysis for a bot using the console or by using the Amazon Lex API. On the Amazon Lex console, choose the **Settings** tab for your bot, then set the **Sentiment Analysis** option to **Yes**. If you are using the API, call the [PutBot](API_PutBot.md) operation with the `detectSentiment` field set to `true`. 

When sentiment analysis is enabled, the response from the [PostContent](API_runtime_PostContent.md) and [PostText](API_runtime_PostText.md) operations return a field called `sentimentResponse` in the bot response with other metadata. The `sentimentResponse` field has two fields, `SentimentLabel` and `SentimentScore`, that contain the result of the sentiment analysis. If you are using a Lambda function, the `sentimentResponse` field is included in the event data sent to your function.

The following is an example of the `sentimentResponse` field returned as part of the `PostText` or `PostContent` response. The `SentimentScore` field is a string that contains the scores for the response.

```
{
    "SentimentScore": 
        "{
        Mixed: 0.030585512690246105,
        Positive: 0.94992071056365967,
        Neutral: 0.0141543131828308,
        Negative: 0.00893945890665054
        }",
    "SentimentLabel": "POSITIVE"
}
```

Amazon Lex calls Amazon Comprehend on your behalf to determine the sentiment in every utterance processed by the bot. By enabling sentiment analysis, you agree to the service terms and agreements for Amazon Comprehend. For more information about pricing for Amazon Comprehend, see [Amazon Comprehend Pricing](https://aws.amazon.com/comprehend/pricing/).

For more information about how Amazon Comprehend sentiment analysis works, see [ Determine the Sentiment ](https://docs.aws.amazon.com/comprehend/latest/dg/how-sentiment.html) in the *Amazon Comprehend Developer Guide*.

# Tagging Your Amazon Lex Resources
Tagging Resources

To help you manage your Amazon Lex bots, bot aliases, and bot channels, you can assign metadata to each resource as *tags.* A tag is a label that you assign to an AWS resource. Each tag consists of a key and a value.

Tags enable you to categorize your AWS resources in different ways, for example, by purpose, owner, or application. Tags help you to:
+ Identify and organize your AWS resources. Many AWS resources support tagging, so you can assign the same tag to resources in different services to indicate that the resources are related. For example, you can tag a bot and the Lambda functions that it uses with the same tag.
+ Allocate costs. You activate tags on the AWS Billing and Cost Management dashboard. AWS uses the tags to categorize your costs and deliver a monthly cost allocation report to you. For Amazon Lex, you can allocate costs for each alias using tags specific to the alias, except for the `$LATEST` alias. You allocate costs for the `$LATEST` alias using tags for your Amazon Lex bot. For more information, see [ Use Cost Allocation Tags ](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*.
+ Control access to your resources. You can use tags to Amazon Lex to create policies to control access to Amazon Lex resources. These policies can be attached to an IAM role or user to enable tag-based access control. For more information, see [ABAC with Amazon Lex](security_iam_service-with-iam.md#security_iam_service-with-iam-tags). To view an example identity-based policy for limiting access to a resource based on the tags on that resource, see [Use a Tag to Access a Resource](security_iam_id-based-policy-examples.md#security_iam_id-based-policy-examples-tag). 

You can work with tags using the AWS Management Console, the AWS Command Line Interface, or the Amazon Lex API.



## Tagging Your Resources


If you are using the Amazon Lex console, you can tag resources when you create them, or you can add the tags later. You can also use the console to update or remove existing tags. 

If you are using the AWS CLI or the Amazon Lex API, you use the following operations to manage tags for your resources:
+  [ListTagsForResource](API_ListTagsForResource.md) – view the tags associated with a resource.
+ [PutBot](API_PutBot.md) and [PutBotAlias](API_PutBotAlias.md) – apply tags when you create a bot or a bot alias.
+  [TagResource](API_TagResource.md) – add and modify tags on an existing resource.
+  [UntagResource](API_UntagResource.md) – remove tags from a resource. 

The following resources in Amazon Lex support tagging:
+ Bots - use an Amazon Resource Name (ARN) like the following:
  + `arn:${partition}:lex:${region}:${account}:bot:${bot-name}`
+ Bot aliases - use an ARN like the following:
  + `arn:${partition}:lex:${region}:${account}:bot:${bot-name}:${bot-alias}`
+ Bot channels - use an ARN like the following:
  + `arn:${partition}:lex:${region}:${account}:bot-channel:${bot-name}:${bot-alias}:${channel-name}`

## Tag Restrictions


The following basic restrictions apply to tags on Amazon Lex resources:
+ Maximum number of tags - 50
+ Maximum key length – 128 characters
+ Maximum value length – 256 characters
+ Valid characters for key and value – a–z, A–Z, 0–9, space, and the following characters: \$1 . : / = \$1 - and @
+ Keys and values are case sensitive.
+ Don't use `aws:` as a prefix for keys; it's reserved for AWS use.

# Tagging Resources (Console)


You can use the console to manage tags on a bot, a bot alias, or a bot channel resource. You can add tags when you create a resource, or you can add, modify, or remove tags from existing resources.

**To add a tag when you create a bot**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose **Create** to create a new bot.

1. At the bottom of the **Create your bot** page, choose **Tags**.

1. Choose **Add tag** and add one or more tags to the bot. You can add up to 50 tags.

**To add a tag when you create a bot alias**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose the bot that you want to add the bot alias to.

1. Choose **Settings**.

1. Add the alias name, choose the bot version, and then choose **Add tags**.

1. Choose **Add tag** and add one or more tags to the bot alias. You can add up to 50 tags.

**To add a tag when you create a bot channel**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose the bot that you want to add the bot channel to.

1. Choose **Channels** and then choose the channel that you want to add.

1. Add the details for the bot channel, and then choose **Tags**.

1. Choose **Add tag** and add one or more tags to the bot channel. You can add up to 50 tags.

**To add a tag when you import a bot**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. Choose **Actions** and then choose **Import**.

1. Choose the zip file for importing the bot.

1. Choose **Tags**, then choose **Add tag** to add one or more tags to the bot. You can add up to 50 tags.

**To add, remove, or modify a tag on an existing bot**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. From the left menu, choose **Bots** and then choose the bot that you want to modify.

1. Choose **Settings** and then from the left menu choose **General**.

1. Choose **Tags** and then add, modify, or remove tags for the bot.

**To add, remove, or modify a tag on a bot alias**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. From the left menu, choose **Bots** and then choose the bot that you want to modify.

1. Choose **Settings** and then from the left menu choose **Aliases**.

1. Choose **Manage tags** for the alias that you want to modify, and then add, modify, or remove tags for the bot alias.

**To add, remove, or modify a tag on an existing bot channel**

1. Sign in to the AWS Management Console and open the Amazon Lex console at [https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/).

1. From the left menu, choose **Bots** and then choose the bot that you want to modify.

1. Choose **Channels**.

1. Choose **Tags** and then add, modify, or remove tags for the bot channel.

# Tagging Resources (AWS CLI)


You can use the AWS CLI to manage tags on a bot, a bot alias, or a bot channel resource. You can add tags when you create a bot or a bot alias, or you can add, modify, or remove tags from a bot, a bot alias, or a bot channel.

All of the examples are formatted for Linux and macOS. To use the command in Windows, replace the Linux continuation character (\$1) with a caret (^).

**To add a tag when you create a bot**
+ The following abbreviated `put-bot` AWS CLI command shows the parameters that you must use to add a tag when you create a bot. To actually create a bot, you must supply other parameters. For more information, see [Step 4: Getting Started (AWS CLI)](gs-cli.md).

  ```
  aws lex-models put-bot \
      --tags '[{"key": "key1", "value": "value1"}, \
               {"key": "key2", "value": "value2"}]'
  ```

**To add a tag when you create a bot alias**
+ The following abbreviated `put-bot-alias` AWS CLI command shows the parameters that you must use to add a tag when you create a bot alias. To actually create a bot alias, you must supply other parameters. For more information, see [Exercise 5: Create an Alias (AWS CLI)](gs-cli-create-alias.md).

  ```
  aws lex-models put-bot \
      --tags '[{"key": "key1", "value": "value1"}, \
               {"key": "key2", "value": "value2"}]"
  ```

**To list tags on a resource**
+ Use the `list-tags-for-resource` AWS CLI command to show the resources associated with a bot, bot alias, bot channel. 

  ```
  aws lex-models list-tags-for-resource \
      --resource-arn bot, bot alias, or bot channel ARN
  ```

**To add or modify tags on a resource**
+ Use the `tag-resource` AWS CLI command to add or modify a bot, bot alias, or bot channel.

  ```
  aws lex-models tag-resource \
      --resource-arn bot, bot alias, or bot channel ARN \
      --tags '[{"key": "key1", "value": "value1"}, \
               {"key": "key2", "value": "value2"}]'
  ```

**To remove tags from a resource**
+ Use the `untag-resource` AWS CLI command to remove tags from a bot, bot alias, or bot channel.

  ```
  aws lex-models untag-resource \
      --resource-arn bot, bot alias, or bot channel ARN \
      --tag-keys '["key1", "key2"]'
  ```