

# Adding intents
<a name="add-intents"></a>

Intents are the goals that your users want to accomplish, such as ordering flowers or booking a hotel. Your bot must have at least one intent.

By default, all bots contain a single built-in intent, the fallback intent. This intent is used when Amazon Lex V2 does not recognize any other intent. For example, if a user says "I want to order flowers" to a hotel booking intent, the fallback intent is triggered.

**To add an intent**

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 list of bots, choose the bot that you want to add the intent to, then from **Add languages** choose **View languages**.

1. Choose the language to add the intent to, then choose **Intents**.

1. Choose **Add intent**, give your intent a name, and then choose **Add**.

1. In the intent editor, add the details of your intent.
   + **Conversation flow** – Use the conversation flow diagram to see how a dialog with your bot might look. You can choose different sections of the conversation to jump to that section of the intent editor.
   + **Intent details** – Give the intent a name and description to help identify the purpose of the intent. You can also see the unique identifier that Amazon Lex V2 assigned to the intent.
   + **Contexts** – Set the input and output contexts for the intent. A context is a state variable associated with an intent. An output context is set when an intent is fulfilled. An intent with an input context can only be recognized if the context is active. An intent with no input contexts can always be recognized.
   + **Sample utterances** – You should provide 10 or more phrases that you expect your users to use to initiate an intent. Amazon Lex V2 generalizes from these phrases to recognize that the user wants to initiate the intent.
   + **Initial response** – The initial message sent to the user after the intent is invoked. You can provide responses, initialize values, and define the next step that Amazon Lex V2 takes to respond to the user at the beginning of the intent.
   + **Slots** – Define the slots, or parameters, required to fulfill the intent. Each slot has a type that defines the values that can be entered in the slot. You can choose from your custom slot types, or you can choose a built-in slot type.
   + **Confirmation** – These prompts and responses are used to confirm or decline fulfillment of the intent. The confirmation prompt asks the user to review slot values. For example, "I've booked a hotel room for Friday. Is this correct?" The declination response is sent to the user when they decline the confirmation. You can provide responses, set values, and define the next step that Amazon Lex V2 takes corresponding to a confirmation or declination response from the user.
   + **Fulfillment** – Response sent to the user during the course of fulfillment. You can set fulfillment progress updates at the start of fulfillment and periodically while the fulfillment is in progress. For example, "I'm changing your password, this may take a few minutes" and "I'm still working on your request." Fulfillment updates are used only for streaming conversations. You can also set a post-fulfillment success message, a failure message, and a timeout message. You can send post-fulfillment messages for both streaming and regular conversations. For example, if the fulfillment succeeds, you can send "I've changed your password." If the fulfillment doesn't succeed, you can send a response with more information, such as "I couldn't change your password, contact the help desk for assistance." If the fulfillment takes longer than the configured timeout period, you can send a message informing the user, such as "Our servers are very busy right now. Try your request again later." You can provide responses, set values, and define the next step that Amazon Lex V2 takes to respond to the user. 
   + **Closing responses** – Response sent to the user after the intent is fulfilled and all other messages are played. For example, a thank you for booking a hotel room. Or it can prompt the user to start a different intent, such as, "Thank you for booking a room, would you like to book a rental car?" You can provide responses and configure follow-up next actions after fulfilling the intent and responding with the closing response.
   + **Code hooks** – Indicate whether you are using an AWS Lambda function to initialize the intent and validate user input. You specify the Lambda function in the alias that you use to run the bot.

1. Choose **Save intent** to save the intent.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

## Configuring prompts in a specific order
<a name="configuring-prompts"></a>

You can configure the bot to play messages in a predefined order by checking the box for **Play messages in order**. Otherwise, the bot plays the message and the variations in random order. 

Ordered prompts allow the message and variations of a message group to play in order among retries. You can use alternate rephrasing of a message when an invalid response for the prompt is given by the user, or for intent confirmation. Up to two variations of the original message may be set in each slot. You can choose whether to play the messages in order or randomly.

Ordered prompt supports all four types of messages: text, custom payload response, SSML, and card group. Responses are ordered within the same message group. Different message groups are independent.

**Topics**
+ [Configuring prompts in a specific order](#configuring-prompts)
+ [Sample utterances](sample-utterances.md)
+ [Intent structure](intent-structure.md)
+ [Creating conversation paths](building-paths.md)
+ [Using Visual conversation builder](visual-conversation-builder.md)
+ [Built-in intents](built-in-intents.md)

# Sample utterances
<a name="sample-utterances"></a>

You create sample utterances that are variations of phrases that you expect users to use to initiate an intent. For example, for a **BookFlight** intent, you might include utterances such as the following:

1. I want to book a flight

1. help me get a flight.

1. plane tickets, please\$1

1. flight from \$1*DepartureCity*\$1 to \$1*DestinationCity*\$1

You should provide 10 or more sample utterances. Give samples that represent a wide range of sentence structures and words that users may utter. Consider incomplete sentences as well, such as in examples 3 and 4 above. You can also use slots that you have defined for the intent in a sample utterance by wrapping curly braces around the slot name, as in \$1*DepartureCity*\$1 in example 4. If you include slot names in a sample utterance, Amazon Lex V2 fills the slots of the intent with the values that the user provides in the utterance.

A variety of sample utterances helps Amazon Lex V2 generalize to effectively recognize that the user wants to initiate the intent.

You can add sample utterances in the intent editor, visual conversation builder, or with the [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) or [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) API operations. You can also generate sample utterances automatically by taking advantage of Amazon Bedrock's generative AI capabilities. For more information, see [Use utterance generation to generate sample utterances for intent recognition](utterance-generation.md).

**Use the Intent editor or Visual conversation builder**

1. In the Intent editor, navigate to the **Sample utterances** section. In the Visual conversation builder, find the **Sample utterances** section in the **Start** block.

1. In the box with the transparent text **I want to book a flight**, type a sample utterance. Select **Add utterance** to add the utterance.

1. View the sample utterances you have added in either **Preview** or **Plain text** mode. In **Plain text**, each line is a separate utterance. In **Preview mode**, hover over an utterance to reveal the following options:
   + Select the text box to edit the utterance.
   + Select the x button on the right of the text box to delete the utterance.
   + Drag the button on the left of the text box to change the order of sample utterances.

1. Use the search bar at the top to search through your sample utterances and the dropdown menu next to it to sort by the order you added the utterances or in alphabetical order.

**Use an API operation**

1. Create a new intent with the [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) operation or update an existing one with the [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) operation.

1. The API request includes a `sampleUtterances` field, which maps to an array of [SampleUtterance](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_SampleUtterance.html) objects.

1. For each sample utterance that you want to add, append a `SampleUtterance` object to the array. Add the sample utterance as the value of the `utterance` field.

1. To edit and delete sample utterances, send an `UpdateIntent` request. The list of utterances you provide in the `sampleUtterances` field replaces the existing utterances.
**Important**  
Any field that you leave blank in the `UpdateIntent` request will cause existing configurations in the intent to be deleted. Use the [DescribeIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DescribeIntent.html) operation to return the bot configuration and copy any configurations that you do not want to be deleted into the `UpdateIntent` request.

# Intent structure
<a name="intent-structure"></a>

Intents are the goals that your users want to accomplish, such as ordering flowers or booking a hotel. Your bot must have at least one intent. An intent is made up of the following components
+ **Initial response** – The initial message sent to the user after the intent is invoked. You can set responses, initialize values, and define the next step that your bot takes to respond to the user at the beginning of the intent.
+ **Slots** – The parameters required to fulfill an intent. Each slot has a type that defines the values that can be entered in the slot. You can choose from your custom slot types or you can choose a built-in slot type.
+ **Confirmation** – After the conversation with the user is complete and the slot values for the intent are filled, you can set a confirmation prompt to ask the user if the slot values are correct.
+ **Fulfillment** – The response sent to a user during the course of fulfillment. You can set fulfillment progress updates at the start of fulfillment and continue sending periodic updates while the fulfillment is in progress. You can also set a post-fulfillment success message, a failure message, and a timeout message.
+ **Closing response** – The closing response sent to the user after their intent is fulfilled. You can set the closing response to end the conversation, or you can set it to let the user know that they can continue with another intent.

**Topics**
+ [Initial response](intent-initial.md)
+ [Slots](intent-slots.md)
+ [Confirmation](intent-confirm.md)
+ [Fulfillment](intent-fulfillment.md)
+ [Closing response](intent-closing.md)

# Initial response
<a name="intent-initial"></a>

The initial response is sent to the user after Amazon Lex V2 determines the intent and before it starts to elicit slot values. You can use this response to inform the user of the intent that was recognized and to prepare them for the information that you collect to fulfill the intent.

For example, if the intent is to schedule a service appointment for a car, the initial response might be:


|  | 
| --- |
| I can help you schedule an appointment. You'll need to provide the make, model, and year of your car. | 

An initial response message isn't required. If you don't provide one, Amazon Lex V2 continues to follow the next step of the initial response.

You can configure the following options within the initial response: 
+ **Configure next step** – You can provide the next step in the conversation such as jumping to a specific dialog action, eliciting a particular slot, or jumping to a different intent. For more information, see [Configure next steps in the conversation](paths-nextstep.md).
+ **Set values** – You can set values for slots and session attributes. For more information, see [Set values during the conversation](paths-setting-values.md)
+ **Add conditional branching** – You can apply conditions after playing the initial response. When a condition evaluates to true, the actions that you define are taken. For more information, see [Add conditions to branch conversations](paths-branching.md).
+ **Execute dialog code hook** – You can define a Lambda code hook to initialize data and execute business logic. For more information, see [Invoke dialog code hook](paths-code-hook.md). If the option to execute Lambda function is enabled for the intent, the dialog code hook is executed by default. You can disable dialog code hook by toggling the **Active**button.

In the absence of a condition or an explicit next step, Amazon Lex V2 moves to the next slot in priority order.

![\[The advanced options for the initial response to a user's request.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-initial.png)


**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Slots
<a name="intent-slots"></a>

Slots are values provided by the user to fulfill the intent. There are two types of slots:
+ **Built-in slot type** – You can use built-in slot types to capture standard values such as number, name, and city. For a list of supported built-in slot types, see [Built-in slot types](built-in-slots.md).
+ **Custom slot type** – You can use custom slot types to capture custom values specific to the intent. For example, you can use a custom slot type to capture account type as “Checking” or “Savings”. For more information, see [Custom slot type](custom-slot-types.md).

To define a slot in an intent, you have to configure the following:
+ **Slot info** – This field contains a name and an optional description for the slot. For example, you can provide slot name as “AccountNumber” to capture account numbers. If the slot is required as part of the conversation flow for fulfilling the intent, it must be marked as required.
+ **Slot type** – A slot type defines the list of values that a slot can accept. You can create a custom slot type or use a pre-defined slot type.
+ **Slot prompt** – A slot prompt is a question posed to the user to gather information. You can configure the number of retries used to gather information and the variation of the prompt used for each retry. You can also enable a Lambda function invocation after each retry to process the input captured and attempt to resolve to a valid input.
+ **Wait and Continue (optional)** – By enabling this behavior, users can say phrases such as "hold on a second" to make the bot wait for them to find the information and provide it. This is enabled only for streaming conversations. For more information, see [Enabling the Amazon Lex V2 bot to wait for the user to provide more information during a pause](wait-and-continue.md).
+ **Slot capture responses** – You can configure a success response and a failure response based on the outcome of capturing the slot value from user input.
+ **Conditional branching** – You can apply conditions after playing the initial response. When a condition evaluates to true, the actions that you define are taken. For more information, see [Add conditions to branch conversations](paths-branching.md).
+ **Dialog code hook** – You can also use a Lambda code hook to validate the slot values and execute business logic. For more information, see [Invoke dialog code hook](paths-code-hook.md).
+ **User input type** – You can configure input type so the bot can accept a specific modality. By default, both audio and DTMF modalities are accepted. You can selectively set it to audio only or DTMF only.
+ **Audio input timeouts and lengths** – You can configure audio timeouts including voice timeout and silence timeout. Also, you can set the max audio length.
+ **DTMF input timeout, characters, and lengths** – You can set the DTMF timeout along with the deletion character and the end character. Also, you can set the max DTMF length. 
+ **Text length** – You can set the max length for text modality.

After the slot prompt is played, the user provides the slot value as an input. If Amazon Lex V2 does not understand a slot value provided by the user, it retries eliciting the slot until it understands a value or until it exceeds the maximum number of retries that you configured for the slot. Using the advanced retry settings you can configure the timeouts, restrict the type of input, and enable or disable interrupt for the initial prompt and retries. After each attempt at capturing the input, Amazon Lex V2 can call the Lambda function configured for the bot with an invocation label provided for retries. You can use the Lambda function, for example, to apply your business logic to attempt resolving it to a valid value. This Lambda function can be enabled within **Advanced options** for slot prompts.

![\[Set up slot prompts to have your bot elicit information.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-slot-prompt.png)


You can define responses that the bot should send to the user once the slot value is entered or if the maximum number of retries is exceeded. For example, for a bot for scheduling service for a car, you can send a message to the user when the vehicle identification number (VIN) is entered:


|  | 
| --- |
| Thank you for providing the VIN number of your car. I will now proceed to schedule an appointment. | 

You can create two responses:
+ **Success response** – sent when Amazon Lex V2 understands a slot value.
+ **Failure response** – sent when Amazon Lex V2 can't understand a slot value from the user after the maximum number of retries.

You can set values, configure the next steps, and apply conditions that correspond to each response to design the conversation flow.

In the absence of a condition or an explicit next step, Amazon Lex V2 moves to the next slot in priority order.

![\[The advanced options for slot responses.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-slot.png)


You can use a Lambda function to validate a slot value that a user has entered and determine what the next action should be. For example, you can use the validation function to make sure that the entered value falls in the correct range, or that is correctly formatted. To activate the Lambda function, choose the **Invoke Lambda function** checkbox and the **Active** button in the **Dialog code hook** section. You can specify an invocation label for the dialog code hook. This invocation label can be used in Lambda function to write the business logic corresponding to the slot elicitation.

![\[The options for dialog code hook.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-dialog-code-hook.png)


Slots that are not required for the intent are not part of the main conversation flow. However, if a user utterance contains a value that your bot identifies as corresponding to an optional slot, it can popluate the slot with that value. For example, if you configure a business intelligence bot to have an optional `City` slot and the user utterance **What is the sales for April in San Diego?**, the bot fills the optional slot with **San Diego**. You can configure the business logic to use the optional slot value, if present.

Slots not required for the intent cannot be elicited using next steps. These steps can be populated only during intent elicitation (as in the preceding example) or can be elicited by setting the dialog state within the Lambda function. If the slot is elicited using the Lambda function, you must use the Lambda function to decide the next step in the conversation after the slot elicitation is completed. To enable support for next step while building the bot, you must mark the slot as required for the intent.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

The following topics describe how to configure a bot to re-elicit a slot value that has already been filled and how to create a slot that consists of multiple values:

**Topics**
+ [Re-eliciting slots](reelicit-slots.md)
+ [Using multiple values in a slot](multi-valued-slots.md)

# Re-eliciting slots
<a name="reelicit-slots"></a>

 You can configure your bot to re-elicit a slot that has already been filled by setting that slot value to **null** and setting the next step in the conversation to loop back to eliciting that slot. For example, you may want to re-elicit a slot after your customer declines a confirmation of the slot elicitation based on extra information, as in the following conversation: 

![\[A conversation eliciting a customer's meat preference for a food order.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/slots/order-food.png)


You can configure a loop from the confirmation response back to re-elicit the slot with either the intent editor or the [Using Visual conversation builder](visual-conversation-builder.md).

**Note**  
You can loop back to re-elicit a slot at any point in the conversation provided that you set that slot value to **null** beforehand.

**Reproducing the above example with the intent editor**

1. In the **Confirmation** section of the intent editor, select the right arrow next to **Prompts to confirm the intent** to expand the section.

1. Select **Advanced options** at the bottom.

1. In the **Decline response** section, select the right arrow next to **Set values** to expand the section. Fill in this section with the following steps, as in the image below:

   1. Set the slot value you want to re-elicit to **null**. In this example, we want to re-elicit the `Meat` slot, so we input **\$1Meat\$1 = null** in the **Slot values** section.

   1. In the dropdown menu under **Next step in conversation**, choose **Elicit a slot**.

   1. A **Slot** section will appear. In the dropdown menu under it, choose the slot you want to re-elicit.

   1. Select **Update options** to confirm your changes.  
![\[A conversation eliciting a customer's meat preference for a food order.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/slots/decline-food.png)

**Reproducing the above example with the Visual conversation builder**

1. Create a connection from the **No** port of the **Confirmation** block to the incoming port of the **Get slot value: Meat** block.  
![\[A connection from the declination of the confirmation prompt to the Meat slot elicitation block.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/slots/vcb-reelicit-slot-loop.png)

1. Select the **Edit** icon in the top right corner of the **Confirmation** block.  
![\[Edit icon in the top right corner of the confirmation block.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/slots/vcb-reelicit-slot-confirmation-edit.png)

1. Select the gear icon next to the bot response in the **Decilne response** section.  
![\[Gear icon next to bot response in decline response section\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/slots/vcb-reelicit-slot-confirmation.png)

1. In the **Set values** section, add "\$1Meat\$1 = null" in the **Slot values** box.  
![\[Set the slot value to be re-elicited to null in the slot values box of the set values section.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/slots/vcb-reelicit-slot-set-slot-null.png)

1. Select **Save Intent.**

# Using multiple values in a slot
<a name="multi-valued-slots"></a>

**Note**  
Multiple value slots are only supported in the English (US) language.

For some intents, you might want to capture multiple values for a single slot. For example, a pizza ordering bot might have an intent with the following utterance:

```
I want a pizza with {toppings}
```

The intent expects that the `{toppings}` slot contains a list of the toppings that the customer wants on their pizza, for example "pepperoni and pineapple".

To configure a slot to capture multiple values, you set the `allowMultipleValues` field on the slot to true. You can set the field using the console or with the [CreateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateSlot.html) or [UpdateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateSlot.html) operation.

You can only mark slots with custom slot types as multi-value slots.

For a multi-value slot, Amazon Lex V2 returns a list of slot values in the response to the [RecognizeText](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeText.html) or [RecognizeUtterance](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_RecognizeUtterance.html) operation. The following is the slot information returned for the utterance "I want a pizza with pepperoni and pineapple" from the OrderPizza bot.

```
    "slots": {
        "toppings": {
            "shape": "List",
            "value": {
                "interpretedValue": "pepperoni and pineapple",
                "originalValue": "pepperoni and pineapple",
                "resolvedValues": [
                    "pepperoni and pineapple"
                ]
            },
            "values": [
                {
                    "shape": "Scalar",
                    "value": {
                        "interpretedValue": "pepperoni",
                        "originalValue": "pepperoni",
                        "resolvedValues": [
                            "pepperoni"
                        ]
                    }
                },
                {
                    "shape": "Scalar",
                    "value:": {
                        "interpretedValue": "pineapple",
                        "originalValue": "pineapple",
                        "resolvedValues": [
                            "pineapple"
                        ]
                    }
                }
            ]
        }
    }
```

Multi-valued slots always return a list of values. When the utterance only contains one value, the list of values returned only contains one response. 

Amazon Lex V2 recognizes multiple values separated by spaces, commas (,), and the conjunction "and". Multi-value slots work with both text and voice input.

You can use multi-valued slots in prompts. For example, you can set the confirmation prompt for an intent to

```
Would you like me to order your {toppings} pizza?
```

When Amazon Lex V2 sends the prompt to the user, it sends "Would you like me to order your pepperoni and pineapple pizza?"

Multi-valued slots support single default values. If multiple default values are provided, Amazon Lex V2 populates the slot with only the first available value. For more information, see [Using default slot values in intents for your Lex V2 bot](context-mgmt-default.md).

You can use slot obfuscation to mask the values of a multi-value slot in conversation logs. When you obfuscate slot values, the value of each of the slot values is replaced with the name of the slot. For more information, see [Obscuring slot values in conversation logs from Lex V2](monitoring-obfuscate.md).

# Confirmation
<a name="intent-confirm"></a>

After the conversation with the user is complete and the slot values for the intent are filled, you can configure a confirmation prompt to ask the user if the slot values are correct. For example, a bot that schedules service appointments for cars might prompt the user with the following:


|  | 
| --- |
| I've got service for your 2017 Honda Civic scheduled for March 25th at 3:00 PM. Is that all right? | 

You can define 3 types of responses to the confirmation prompt:
+ **Confirmation response** – This response is sent to the user when the user confirms the intent. For example, after the user replies "yes" to the prompt "do you want to place the order?"
+ **Decline response** – This response is sent to the user when the user declines the intent. For example, after the user replies "no" to the prompt "do you want to place the order?"
+ **Failure response** – This response is sent to the user when the confirmation prompt can't be processed. For example, if the user's response couldn't be understood or couldn't be resolved to a yes or a no. 

![\[A flowchart showing the 3 types of responses for confirmation and decline responses.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/conditional-confirmation-flow.png)


If you don't specify a confirmation prompt, Amazon Lex V2 moves to the fulfillment step or the closing response. 

You can set values, configure the next steps, and apply conditions corresponding to each response to design the conversation flow. In the absence of a condition or an explicit next step, Amazon Lex V2 moves to the fulfillment step. 

You can also enable the dialog code hook to validate the information captured in the intent prior to sending it for fulfillment. To use a code hook, enable the dialog code hook in the confirmation prompt advanced options. In addition, configure the next step of the previous state to execute the dialog code hook. For more information, see [Invoke dialog code hook](paths-code-hook.md). 

**Note**  
 If you use a code hook to trigger the confirmation step at runtime, you must mark the confirmation step as **Active** at build time. 

![\[The Amazon Lex V2 console showing the advanced options for confirmation prompts.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-confirm.png)


**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

## Using a Lambda function to validate an intent.
<a name="intent-confirm-codehook"></a>

You can define a Lambda code hook to validate the intent before you send it for fulfillment. To use a code hook, enable the dialog code hook in the confirmation prompt advanced options.

When you use a code hook, you can define the actions that Amazon Lex V2 takes after the code hook runs. You can create three types of responses:
+ **Success response** – Sent to the user when the code hook completes successfully.
+ **Failure response** – Sent to the user when the code hook doesn't run successfully or when the code hook returns `Failure` in the response.
+ **Timeout response** – Sent to the user when the code hook does not complete in its configured timeout period.

# Fulfillment
<a name="intent-fulfillment"></a>

After all the slot values are provided by the user for the intent, Amazon Lex V2 fulfills the user’s request. You can configure the following options for fulfillment.
+ **Fulfillment code hook** – You can use this option to control the fulfillment Lambda invocation. If the option is disabled, the fulfillment succeeds without invoking the Lambda function.
+ **Fulfillment updates** – You can enable fulfillment updates for Lambda functions that take more than a few seconds to complete, so that the user knows that the process is in progress. For more information, see [Configuring fulfillment progress updates for your Lex V2 bot](streaming-progress.md). This functionality is only available for streaming conversations.
+ **Fulfillment responses** – You can configure a success response, a failure response, and a timeout response. The appropriate response is returned to the user based on the status of the fulfillment Lambda invocation.

There are three possible fulfillment responses:
+ **Success response** – A message sent when the fulfillment Lambda completes successfully.
+ **Failure response** – A message sent if the fulfillment failed or Lambda can't be completed for some reason.
+ **Timeout response** – A message sent if the fulfillment Lambda function doesn't finish within the configured timeout.

You can set values, configure the next steps, and apply conditions corresponding to each response to design the conversation flow. In the absence of a condition or an explicit next step, Amazon Lex V2 moves to closing response. 

![\[The Amazon Lex V2 console showing the response options for a fulfillment code hook.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-fulfillment.png)


**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Closing response
<a name="intent-closing"></a>

The closing response is sent to your user after their intent is fulfilled. You can use the closing response to end the conversation, or you can use it to let the user know that they can continue with another intent. For example, in a travel booking bot, you can set the closing response for the book hotel room intent to this:


|  | 
| --- |
| All right, I've booked your hotel room. Is there anything else I can help you with?  | 

You can set values, configure the next steps, and apply conditions after the closing response to the design the conversation path. In the absence of a condition or an explicit next step, Amazon Lex V2 ends the conversation. 

If you don't supply a closing response, or if none of the conditions evaluates to true, Amazon Lex V2 ends the conversation with your bot.

![\[The Amazon Lex V2 console showing the options for closing response.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/response-closing.png)


**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Creating conversation paths
<a name="building-paths"></a>

Typically, Amazon Lex V2 manages the flow of conversations with your users. For simple bots, the default flow can be enough to create a good experience for your users. However, for more complex bots, you might want to take control of the conversation and direct the flow into more complex paths.

For example, in a bot that books car rentals, you might not rent to younger drivers. In this case, you can create a condition that checks to see if a driver is below a certain age, and if so, jump to the closing response. 

![\[A flowchart showing the conversation flow for a car rental bot that doesn't rent to drivers under 24.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/conditional-flowchart.png)


To design such interactions, you can configure the next step at each point in the conversation, evaluate conditions, set values and invoke code hooks.

Conditional branching helps you create paths for your users through complex interactions. You can use a conditional branch at any point that you pass control of the conversation to your bot. For example, you can create a condition before the bot elicits the first slot value, you can create a condition between eliciting each slot value, or you can create a condition before the bot closes the conversation. For a list of the places that you can add conditions, see [Adding intents](add-intents.md).

When you create a bot, Amazon Lex V2 creates a default path through the conversation based on the priority order of the slots. To customize the conversation path, you can modify the next step at any point in the conversation. For more information, see [Configure next steps in the conversation](paths-nextstep.md). 

To create alternative paths based on conditions, you can use a conditional branch at any point in the conversation. For example, you can create a condition before the bot elicits the first slot value. You can create a condition between eliciting each slot value, or you can create a condition before the bot closes the conversation. For a list of the places allowing you to add conditions, see [Add conditions to branch conversations](paths-branching.md).

You can set conditions based on slot values, session attributes, the input mode and input transcript, or a response from Amazon Kendra. 

You can set slot and session attribute values at each point in the conversation. For more information, see [Set values during the conversation](paths-setting-values.md).

You can also set the next action to dialog code hook to run a Lambda function. For more information, see [Invoke dialog code hook](paths-code-hook.md). 

The following image shows the creation of a path for a slot in the console. In this example, Amazon Lex V2 will elicit the slot "age". If the value of the slot is less than 24, Amazon Lex V2 jumps to the closing response, otherwise Amazon Lex V2 will follow the default path.

![\[The Amazon Lex V2 console showing the condition editor for a slot.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/conditional-slot.png)


**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Configure next steps in the conversation
<a name="paths-nextstep"></a>

You can configure a next step at each stage of the conversation to design conversations. Typically, Amazon Lex V2 automatically configures the default next steps for each stage of the conversation as per the following order.

 Initial Response → Slot Elicitation → Confirmation (if active) → Fulfillment (if active) → Closing Response (if active) → End conversation

You can modify the default next steps and design the conversation based on the expected user experience. The following next steps can be configured at each stage of the conversation:

**Jump to**
+ **Initial response** – The conversation is restarted from the beginning of the intent. You can choose to skip the initial response while configuring this next step
+ **Elicit a slot** – You can elicit any slot in the intent.
+ **Evaluate conditions** – You can evaluate conditions and branch conversation at any step of the conversation.
+ **Invoke dialog code hook** – You can invoke business logic at any step.
+ **Confirm intent** – The user will be prompted to confirm the intent.
+ **Fulfill intent** – The fulfillment of the intent will begin as a next step.
+ **Closing response** – The closing response will be returned to the user.

**Switch to**
+ **Intent** – You can transition to a different intent and continue the conversation for this intent. You can optionally skip the initial response of the intent while making the transition.
+ **Intent: specific slot** – You can directly elicit a specific slot in a different intent if you have already captured some slot values in the current intent.

**Wait for user input** – The bot waits for the user to provide inputs for recognizing any new intent. You can configure prompts such as "Is there anything else I can help you with?" before setting this next step. The bot will be in `ElicitIntent` dialog state.

**End conversation** – The conversation with the bot is closed.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Set values during the conversation
<a name="paths-setting-values"></a>

Amazon Lex V2 provides the ability to set slot values and session attribute values at every step of the conversation. You can then use these values during the conversation to evaluate conditions or use them during intent fulfillment.

You can set slot values for the current intent. If the next step in the conversation is to invoke another intent, you can set slot values of the new intent.

If the assigned slot is not filled, or if the JSON path cannot be parsed, then the attribute will be set to `null`.

Use the following syntax when using slot values and session attributes:
+ **Slot values** – surround the slot name with braces ("\$1 \$1"). For slot values in the current intent, you only need to use the slot name. For example, `{slot}`. If you are setting a value in the next intent, you must use both the intent name and the slot name to identify the slot. For example, `{intent.slot}`.

  Examples:
  +  `{PhoneNumber} = "1234567890"` 
  +  `{CheckBalance.AccountNumber} = "99999999"` 
  +  `{BookingID} = "ABC123"` 
  +  `{FirstName} = "John"` 

  The value of a slot can be any of the following:
  + a constant string
  + a JSON path that refers to the transcriptions block in the Amazon Lex response (for en-US and en-GB)
  + a session attribute

  Examples:
  +  `{username} = "john.doe" ` 
  +  `{username_confidence} = $.transcriptions[0].transcriptionConfidence ` 
  +  `{username_slot_value} = [username] ` 
**Note**  
Slot values can also be set to `null`. If you need to re-elicit a slot value that has been filled, you must set the value to `null` before prompting the customer for the slot value again. If the assigned slot is not filled, or if the JSON path cannot be parsed, then the attribute will be set to `null`.
+ **Session attributes** – surround the attribute name with square brackets ("[ ]"). For example, `[sessionAttribute]`.

  Examples:
  +  ` [username] = "john.doe" ` 
  +  ` [username_confidence] = $.transcriptions[0].transcriptionConfidence ` 
  +  ` [username_slot_value] = {username} ` 

  The value of the session attribute can be any of the following:
  + a constant string
  + a JSON path that refers to the transcriptions block in the Amazon Lex response (for en-US and en-GB)
  + a slot value reference
**Note**  
If the assigned slot is not filled, or if the JSON path cannot be parsed, then the attribute will be set to `null`.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Add conditions to branch conversations
<a name="paths-branching"></a>

You can use *conditional branching* to control the path that your customer takes through the conversation with your bot. You can branch the conversation based on slot values, session attributes, the contents of the input mode and input transcript fields, or a response from Amazon Kendra.

You can define up to four branches. Each branch has a condition that must be satisfied in order for Amazon Lex V2 to follow that branch. If none of the branches has its condition satisfied, a default branch is followed.

When you define a branch, you define the action that Amazon Lex V2 should take if the conditions corresponding to that branch evaluate to true. You can define any of the following actions:
+ A response sent to the user.
+ Slot values to apply to slots.
+ Session attribute values for the current session.
+ The next step in the conversation. For more information, see [Creating conversation paths](building-paths.md).

![\[You can choose different options for conditional branching.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/conditional-choose.png)


Each conditional branch has a Boolean expression that must be satisfied for Amazon Lex V2 to follow the branch. There are comparison and Boolean operators, functions, and quantifier operators that you can use for your conditions. For example, the following condition returns true if the \$1age\$1 slot is less than 24.

```
{age} < 24
```

The following condition returns true if the \$1toppings\$1 multi-value slot contains the word "pineapple".

```
{toppings} CONTAINS "pineapple"
```

You can combine multiple comparison operators with a Boolean operator for more complex conditions. For example, the following condition returns true if the \$1make\$1 slot value is "Honda" and the \$1model\$1 slot value is "Civic". Use parentheses to set the evaluation order.

```
({make} = "Honda") AND ({model} = "Civic")
```

The following topics provide details on the conditional branch operators and functions.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

**Topics**
+ [Comparison operators](#branching-comparison)
+ [Boolean operators](#branching-boolean)
+ [Quantifier operators](#branching-quentifier)
+ [Functions](#branching-function)
+ [Sample conditional expressions](#sample-conditional-expressions)

## Comparison operators
<a name="branching-comparison"></a>

Amazon Lex V2 supports the following comparison operators for conditions:
+ Equals (=)
+ Not equals (\$1=)
+ Less than (<)
+ Less than or equals (<=)
+ Greater than (>)
+ Greater than or equals (>=)

When using a comparison operator, it uses the following rules.
+ The left-hand side must be a reference. For example, to reference a slot value, you use `{slotName}`. To reference a session attribute value, you use `[attribute]`. For input mode and input transcript, you use `$.inputMode` and `$.inputTranscript`.
+ The right-hand side must be a constant and the same type as the left hand side.
+ Any expression referencing an attribute which has not been set is treated as invalid, and is not evaluated.
+ When you compare a multi-valued slot, the value used is a comma-separated list of all interpreted values.

Comparisons are based on the slot type of the reference. They are resolved as follows:
+ **Strings ** – strings are compared based on their ASCII representation. The comparison is case-insensitive.
+ **Numbers** – number-based slots are converted from the string representation to a number and then compared.
+ **Date/Time** – time-based slots are compared based on the time series. The earlier date or time is considered smaller. For durations, shorter periods are considered smaller. 

## Boolean operators
<a name="branching-boolean"></a>

Amazon Lex V2 supports Boolean operators to combine comparison operators. They let you create statements similar to the following:

```
({number} >= 5) AND ({number} <= 10)
```

You can use the following Boolean operators:
+ AND (&&)
+ OR (\$1\$1)
+ NOT (\$1)

## Quantifier operators
<a name="branching-quentifier"></a>

Quantifier operators evaluate the elements of a sequence and determine if one or more elements satisfy the condition.
+ **CONTAINS** – determines if the specified value is contained in a multi-valued slot and returns true if it is. For example, `{toppings} CONTAINS "pineapple"` returns true if the user ordered pineapple on their pizza.

## Functions
<a name="branching-function"></a>

Functions must be prefixed with the string `fn.`. The argument to the function is a reference to a slot, session attribute, or request attribute. Amazon Lex V2 provides two functions for getting information from the values of slots, sessionAttribute, or requestAttribute.
+ **fn.COUNT()** – counts the number of values in a multi-valued slot. 

  For example, if the slot `{toppings}` contains the value "pepperoni, pineapple":

  `fn.COUNT({toppings}) = 2`
+ **fn.IS\$1SET()** – value is true if a slot, session attribute, or request attribute is set in the current session.

  Based on the previous example:

  `fn.IS_SET({toppings})`
+ **fn.LENGTH()** – value is the length of the value of the session attribute, slot value, or slot attribute which is set in the current session. This function does not support multi-value slots or composite slots.

  Example:

  If the slot `{credit-card-number}` contains the value "123456781234":

  `fn.LENGTH({credit-card-number}) = 12`

## Sample conditional expressions
<a name="sample-conditional-expressions"></a>

Here are some sample conditional expressions. NOTE: `$.` represents the entry point to the Amazon Lex V2 JSON response. The value following `$.` will be parsed within the Amazon Lex V2 response to retrieve the value. Conditional expressions using the JSON path reference to transcriptions block in the Amazon Lex V2 response will only be supported in the same locales which support ASR transcription scores.


| Value type | Use case | Conditional expression | 
| --- | --- | --- | 
| Custom slot | pizzaSize slot value is equal to large | \$1pizzaSize\$1 = "large" | 
| Custom slot | pizzaSize is equal to large or medium | \$1pizzaSize\$1 = "large" OR \$1pizzaSize\$1 = "medium"  | 
| Custom slot | Expressions with () and AND/OR | \$1pizzaType\$1 = "pepperoni" OR \$1pizzaSize\$1 = "medium" OR \$1pizzaSize\$1 = "small"  | 
| Custom slot (Multi-Valued Slot) | Check if one of the topping is Onion | \$1toppings\$1 CONTAINS "Onion" | 
| Custom slot (Multi-Valued Slot) | Number of toppings are more than 3 | fn.COUNT(\$1topping\$1) > 2 | 
| AMAZON.AlphaNumeric | bookingID is ABC123 | \$1bookingID\$1 = "ABC123" | 
| AMAZON.Number | age slot value is greater than 30 | \$1age\$1 > 30 | 
| AMAZON.Number | age slot value is equal to 10 | \$1age\$1 = 10 | 
| AMAZON.Date | dateOfBirth slot value before 1990 | \$1dateOfBirth\$1 < "1990-10-01" | 
| AMAZON.State | destinationState slot value is equal to Washington | \$1destinationState\$1 = "washington" | 
| AMAZON.Country | destinationCountry slot value is not United States | \$1destinationCountry\$1 \$1= "united states" | 
| AMAZON.FirstName | firstName slot value is John | \$1firstName\$1 = "John" | 
| AMAZON.PhoneNumber | phoneNumber slot value is 716767891932 | \$1phoneNumer\$1 = 716767891932 | 
| AMAZON.Percentage | Check if percentage slot value is greater than or equals 78 | \$1percentage\$1 >= 78 | 
| AMAZON.EmailAddress | emailAddress slot value is userA@hmail.com | \$1emailAddress\$1 = "userA@hmail.com" | 
| AMAZON.LastName | lastName slot value is Doe | \$1lastName\$1 = "Doe" | 
| AMAZON.City | City slot value is equal to Seattle | \$1city\$1 = "Seattle" | 
| AMAZON.Time | Time is after 8 PM | \$1time\$1 > "20:00" | 
| AMAZON.StreetName | streetName slot value is Boren Avenue | \$1streetName\$1 = "boren avenue" | 
| AMAZON.Duration | travelDuration slot value is less than 2 hours | \$1travelDuration\$1 < P2H | 
| Input mode | Input mode is speech | \$1.inputMode = "Speech" | 
| Input transcript | Input transcript is equal to "I want a large pizza" | \$1.inputTranscript = "I want a large pizza" | 
| Session attribute | check customer\$1subscription\$1type attribute | [customer\$1subcription\$1type] = "yearly" | 
| Request attribute | check retry\$1enabled flag | ((retry\$1enabled)) = "TRUE" | 
| Kendra response | Kendra response contains FAQ | fn.IS\$1SET(((x-amz-lex:kendra-search-response-question\$1answer-question-1))) | 
| Conditional expression with transcriptions | Conditional expressions using transcriptions JSON path | \$1.transcriptions[0].transcriptionConfidence < 0.8 AND \$1.transcriptions[1].transcriptionConfidence > 0.5 | 
| Set session attributes | Set session attributes using transcriptions JSON path and slot values | [sessionAttribute] = "\$1.transcriptions..." AND [sessionAttribute] = "\$1<slotName>\$1" | 
| Set slot values | Set slot values using session attributes and transcriptions JSON path | \$1slotName\$1 = [<sessionAttribute>] AND \$1slotName\$1 = "\$1.transcriptions..." | 

**Note**  
`slotName` refers to the name of a slot in the Amazon Lex V2 bot. If the slot is not resolved (null), or if the slot does not exist, then the assignments are ignored at runtime. `sessionAttribute` refers to the name of the session attribute that is set by the customer at build time.

# Invoke dialog code hook
<a name="paths-code-hook"></a>

At each step in the conversation when Amazon Lex V2 sends a message to the user, you can use a Lambda function as the next step in the conversation. You can use the function to implement business logic based on current state of the conversation.

The Lambda function that runs is associated with the bot alias that you are using. To invoke Lambda function across all dialog code hooks in your intent, you must select **Use a Lambda function for initializing and validation** for the intent. For more information on choosing a Lambda function, see [Creating an AWS Lambda function for your Amazon Lex V2 bot](lambda-attach.md).

There are two steps to using a Lambda function. First, you must activate the dialog code hook at any point in the conversation. Second, you must set the next step in the conversation to use the dialog code hook.

The following image shows the dialog code hook activated.

![\[Shows that the conditional response code hook is active.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/code-hook-active.png)


Next, set the code hook as the next action for the conversation step. You can do this by configuring the next step in conversation to Invoke dialog code hook. The following image shows a conditional branch where invoking the dialog code hook is the next step for the default path of the conversation.

![\[Conditional branching showing a code hook as the next step in the conversation.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/code-hook-choose.png)


When code hooks are active, you can set three responses to return to the user:
+ **Success** – Sent when the Lambda function completed successfully.
+ **Failure** – Sent if there was a problem with running the Lambda function, or the Lambda function returned an `intent.state` value of `Failed`.
+ **Timeout** – Sent if the Lambda function did not complete in its configured timeout period.

![\[Flowchart showing the options available for messages after a Lambda function runs.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/conditional-code-hook.png)


Choose **Lambda dialog code hook** and then choose **Advanced options** to see the three options for responses that correspond to the Lambda function invocation. You can set values, configure the next steps, and apply conditions corresponding to each response to design the conversation flow. In the absence of a condition or an explicit next step, Amazon Lex V2 decides the next step based on the current state of the conversation. 

On the **Advanced options** page you can also choose to enable or disable your Lambda function invocation. When the function is enabled, the dialog code hook is invoked with Lambda invocation, followed by the success, failure or timeout message based on Lambda invocation results. When the function is disabled, Amazon Lex V2 doesn't run the Lambda function and proceeds as if the dialog code hook is successful.

You can also set an invocation label that is sent to the Lambda function when it is invoked by this message. You can use this to help identify the section of your Lambda function to run.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Using Visual conversation builder
<a name="visual-conversation-builder"></a>

Visual conversation builder is a drag and drop conversation builder to easily design and visualize conversation paths by using intents within a rich visual environment.

**To access the visual conversation builder**

1. In the Amazon Lex V2 console, choose a bot and select **Intents** from the left navigation pane.

1. Go to the intent editor in one of the following ways:
   + Select **Add intent** at the top-right corner of the **Intents** section, and then choose to add either an empty intent or a built-in intent.
   + Choose the name of an intent from the **Intents** section.

1. In the intent editor, select **Visual builder** in the pane at the bottom of the screen to access the Visual conversation builder.

1. To return to the menu intent editor interface, select **Editor**.

![\[A sample conversation flow with visual conversation builder.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-sample.png)


Visual conversation builder offers a more intuitive user interface with the ability to visualize and modify the conversation flow. By dragging and dropping the blocks, you can extend an existing flow or reorder the conversation steps. You can develop conversation flow with complex branching without writing any Lambda code.

This change helps to decouple the conversation flow design from other business logic in Lambda. Visual conversation builder can be used in conjunction with the existing intent editor and can be used to build conversation flows. However, it is recommended to use the visual editor view for more complex conversation flows.

When you save an intent, Amazon Lex V2 can auto-connect intents when it determines that there are missed connections, Amazon Lex V2 suggests a connection, or you can select your own connection for the block.


| Action | Example | 
| --- | --- | 
|  Adding a block to the workspace  |  ![\[Adding a block onto the workspace\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-addblock.gif)  | 
|  Making a connection between blocks  |  ![\[Making a connection between blocks\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-connectionblock.gif)  | 
|  Opening the configuration panel on a block  |  ![\[Open the configuration panel of a block\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-openpanelblock.gif)  | 
|  Zoom to fit  |  ![\[Zoom to fit\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-zoomtofit.gif)  | 
|  Delete a block from the conversation flow  |  ![\[Delete a block from the conversation flow\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-deleteblock.gif)  | 
|  Auto clean the workspace  |  ![\[Auto clean the workspace\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-autoclean.gif)  | 

**Terminology:**

**Block** – The basic building unit of a conversation flow. Each block has a specific functionality to handle different use cases of a conversation.

**Port** – Each block contains ports, which can be used to connect one block to another. Blocks can contain input ports and output ports. Each output port represents a particular functional variation of a block (such as errors, timeouts, or success).

**Edge** – An edge is a connection between the output port of one block to the input port of another block. It is a part of a branch in a conversation flow.

**Conversation flow** – A set of blocks connected by edges that describes intent level interactions with a customer. 

**Blocks**

Blocks are the building blocks of a conversation flow design. They represent different states within the intent, that spans from the start of the intent, to user input, to the closing.

Each block has an entry point and one or many exit points based on the block type. Each exit point can be configured with a corresponding message as the conversation proceeds through the exit points. For blocks with multiple exit points, exit points relate to the status corresponding to the node. For a condition node, the exit points represent the different conditions.

Each block has a configuration panel, which opens by clicking on the **Edit** icon on the top right corner of the block. The configuration panel contains detailed fields that can be configured to correspond with each block.

The bot prompts and messages can be configured directly on the node by dragging a new block, or they can be modified within the right panel, along with other attributes of the block.

**Block types** – Here are the block types that you can use with visual conversation builder.


| Block Type | Block | 
| --- | --- | 
|  **Start** – The root or first block of the conversation flow. This block can also be configured such that the bot can send an initial response (message the intent has been recognized). For more information, see [Initial response](intent-initial.md).  |  ![\[A start block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-start.png)  | 
|  **Get slot value** – This block tries to elicit value for a single slot. This block has a setting to wait for customer response to the slot elicitation prompt. For more information, see [Slots](intent-slots.md).  |  ![\[A get slot value block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-getslotvalue.png)  | 
|  **Condition** – This block contains conditionals. It contains up to 4 custom branches (with conditions) and one default branch. For more information, see [Add conditions to branch conversations](paths-branching.md).  |  ![\[A condition block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-condition.png)  | 
|  **Dialog code hook** – This block handles invocation of the dialog Lambda function. This block contains bot responses based on dialog Lambda function succeeding, failing, or timing out. For more information, see [Invoke dialog code hook](paths-code-hook.md).  |  ![\[A code hook block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-codehook.png)  | 
|  **Confirmation** – This block queries the customer before fulfillment of the intent. It contains bot responses based on customer saying yes or no to the confirmation prompt. For more information, see [Confirmation](intent-confirm.md).  |  ![\[A confirmation block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-confirmation.png)  | 
|  **Fulfillment** – This block handles fulfillment of intent, usually after slots elicitation. It can be configured to invoke Lambda functions, as well as respond with messages, if fulfillment succeeds or fails. For more information, see [Fulfillment](intent-fulfillment.md).  |  ![\[A fulfillment block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-fulfillment.png)  | 
|  **Closing response** – This block allows the bot to respond with a message before ending the conversation. For more information, see [Closing response](intent-closing.md).  |  ![\[A closing block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-closing.png)  | 
|  **End conversation** – This block indicates the end of the conversation flow.  |  ![\[An end block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-end.png)  | 
|  **Wait for user input** – This block can be used to capture input from the customer and switch to another intent based on the utterance.  |  ![\[A wait block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-wait.png)  | 
|  **Go to intent** – This block can be used to go to a new intent, or to directly elicit a specific slot of that intent.  |  ![\[A go to intent block in visual conversation builder\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/vcb-gotointent.png)  | 

**Port types**

All blocks contain one input port, which is used to connect its parent blocks. The conversation can only flow to a particular block’s input port from its parent block’s output port. However, blocks can contain zero, one, or many output ports. The blocks without any output ports signify the end of the conversation flow in the current intent (`GoToIntent`, `EndConversation`,`WaitForUserInput`). 

**Rules of intent design:**
+ All flows in an intent begin with the start block.
+ Messages corresponding to each exit point are optional.
+ You can configure the blocks to set values corresponding to each exit point in the configuration panel.
+ Only a single start, confirmation, fulfillment and closing blocks can exist in a single flow within an intent. Multiple conditions, dialog code hook, get slot values, end conversation, transfer, and wait for user input blocks may exist.
+ A condition block cannot have a direct connection to a condition block. The same applies for dialog code hook.
+ Circular flows are allowed three blocks, but an incoming connector to Start Intent is not allowed.
+ An optional slot doesn’t have an incoming connector or an outgoing connection and is primarily used to capture any data present during intent elicitation. Every other slot that is part of the conversation path must be a mandatory slot.

Blocks:
+ The start block must have an outgoing edge.
+ Every get slot value block must have an outgoing edge from the success port, if the slot is required.
+ Every condition block must have an outgoing edge from each branch if the block is active.
+ A condition block cannot have more than one parent.
+ An active condition block must have an incoming edge.
+ Every active code hook block must have an outgoing edge from each port: success, failure, and timeout.
+ An active code hook block must have an incoming edge.
+ An active confirmation block must have an incoming edge.
+ An active fulfillment block must have an incoming edge.
+ An active closing block must have an incoming edge.
+ A condition block must have at least one non-default branch.
+ A go to intent block must have an intent specified.

Edges:
+ A condition block cannot be connected to another condition block.
+ A code hook block cannot be connected to another code hook block.
+ A condition block can only be connected to zero or one code hook block.
+ The connection (code hook -> condition -> code hook) is not valid.
+ A fulfillment block cannot have a code hook block as a child.
+ A condition block, which is a child of the fulfillment block, cannot have a code hook block child.
+ A closing block cannot have a code hook block as a child.
+ A condition block that is a child of the closing block cannot have a code hook block child.
+ A start, confirmation, or get slot value block can have no more than one code hook block in its dependency chain.

**Note**  
On August 17, 2022, Amazon Lex V2 released a change to the way conversations are managed with the user. This change gives you more control over the path that the user takes through the conversation. For more information, see [Changes to conversation flows in Amazon Lex V2](understanding-new-flows.md). Bots created before August 17, 2022 do not support dialog code hook messages, setting values, configuring next steps, and adding conditions.

# Built-in intents
<a name="built-in-intents"></a>

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 left menu, choose the language and then choose **Intents**.

1. Choose **Add intent**, and then choose **Use built-in intent**.

1. In **Built-in intent**, choose the intent to use.

1. Give the intent a name, and then choose **Add**.

1. Use the intent editor to configure the intent as required for your bot.

**Topics**
+ [AMAZON.BedrockAgentIntent](built-in-intent-bedrockagent.md)
+ [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.QnAIntent](built-in-intent-qna.md)
+ [AMAZON.QnAIntent (multiple use support)](built-in-intent-qna-multi.md)
+ [AMAZON.QinConnectIntent](built-in-intent-qinconnect.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)

# AMAZON.BedrockAgentIntent
<a name="built-in-intent-bedrockagent"></a>

**Note**  
Before you can take advantage of the generative AI features, you must fulfill the following prerequisites  
For information about pricing for using Amazon Bedrock, see [Amazon Bedrock pricing](https://aws.amazon.com/bedrock/pricing/).
Turn on the generative AI capabilities for your bot locale. To do so, follow the steps at [Optimize Lex V2 bot creation and performance by using generative AI](generative-features.md). 

Activates Amazon Bedrock Agents that are defined in the intent to respond to customer requests and activate agentic workflows to achieve the task defined. This feature is available in all Amazon Lex V2 supported locales and all commercial regions where both Amazon Lex V2 and Amazon Bedrock Agents are present. 

If this intent is overriding `FallbackIntent`, the intent is activated when an utterance is not classified into any of the other intents present in the bot, otherwise it is only activated when an utterance is classified into this intent. It’s important to note that this intent will not be activated for missed utterances when eliciting a slot value. 

Once recognized by your Amazon Lex V2 bot, the `AMAZON.BedrockAgentIntent`, activates the defined `BedrockAgent` or `BedrockKnowledgeBase` to respond to the customer. If you are using Amazon Bedrock Agents, the conversation stays in the `BedrockAgentIntent` and the user requests are relayed to Agents, until the Amazon Bedrock Agent determines that the conversation is marked `FINISH`. Only after that, Amazon Lex V2 assumes control of the conversation and adheres to next steps defined in the `AMAZON.BedrockAgentIntent`.

Responds to customer questions by using an Amazon Bedrock Agents and Knowledge Bases to answer customer questions and provide detailed responses.

**Warning**  
You can't use the `AMAZON.BedrockAgentIntent` without sample utterances, `AMAZON.QnAIntent` without sample utterances and the `AMAZON.KendraSearchIntent` in the same bot locale.

If you select this intent, you configure the following fields and then select Add to add the intent.
+ Amazon Bedrock Agent Id - The identifier of the Amazon Bedrock Agent. Choose the Bedrock Agent that you want to use. 
+ Amazon Bedrock Agent Alias Id - The Alias identifier of the Amazon Bedrock Agent.

**Important**  
When creating the Amazon Bedrock Agent to be used with Amazon Lex V2, verify that **User Input** under **Additional Settings** is `ENABLED`. This setting is critical to allow Agents to ask clarifying or follow-up questions, and it allows Amazon Lex V2 to delegate back to Agents to complete the corresponding task.

(Optional) You can also add a BedrockAgentIntent with these options:
+ Amazon Bedrock model - Choose the provider and foundation model to use for this intent. Currently, some Anthropic Claude models are supported. 
+ Amazon Bedrock Knowledge Base - If you choose this option, specify the ID of the Amazon Bedrock Knowledge Base. You can find the ID by checking the details page of the Amazon Bedrock Knowledge Base in the console, or by sending a `GetKnowledgeBase` request.

The responses from the BedrockAgentIntent will be stored into the session and request attributes as shown below:
+ `x-amz-lex:bedrock-agent-search-response` – The response from the Amazon Bedrock Agent to the question or utterance.
+ `x-amz-lex:bedrock-knowledge-base-search-response-source` – Points to the document, or list of documents, used to generate the response if using the Amazon Bedrock Knowledge Base configuration.
+ `x-amz-lex:bedrock-agent-action-group-invocation-input` - Object containing input values collected by the agent action group. For more information on agent action groups, see ActionGroupInvocationInput.
+ `x-amz-lex:bedrock-agent-knowledge-base-lookup-input` - Object containing the Amazon Bedrock Knowledge Base lookup related details.
+ `x-amz-lex:bedrock-agent-agent-collaborator-details` – Object containing details of the input and output from the sub agents that were invoked as part of Multi-agent collaboration invocations.

For more information, see [Using BedrockAgentIntent to use a Bedrock Agent in Amazon Lex](https://docs.aws.amazon.com/lexv2/latest/dg/bedrock-agent-intent.html).

# AMAZON.CancelIntent
<a name="built-in-intent-cancel"></a>

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
<a name="built-in-intent-fallback"></a>

When a user's input to an intent isn't what a bot expects, you can configure Amazon Lex V2 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 V2 invokes the fallback intent to handle the response.

The built-in `AMAZON.FallbackIntent` intent type is added to your bot automatically when you create a bot using the console or when you add a locale to a bot using the [CreateBotLocale](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateBotLocale.html) operation. 

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. 

Amazon Lex V2 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 V2 can't determine which intent to invoke.

The fallback intent is invoked when:
+ 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't add the following to a fallback intent:
+ Utterances
+ Slots
+ A confirmation prompt

## Using a Lambda Function with a Fallback Intent
<a name="invoke-fallback"></a>

When a fallback intent is invoked, the response depends on the setting of the `fulfillmentCodeHook` parameter to the [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) operation. The bot does one of the following:
+ Returns the intent information to the client application.
+ Calls the alias's validation and 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 `fulfillmentCodeHook` parameter of the [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) operation. 

If you use the Lambda function with 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.

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 V2 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 your 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 for your Lex V2 bot](context-mgmt-session-attribs.md).

# AMAZON.HelpIntent
<a name="built-in-intent-help"></a>

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
<a name="built-in-intent-kendra-search"></a>

To search documents that you have indexed with Amazon Kendra, use the `AMAZON.KendraSearchIntent` intent. When Amazon Lex V2 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 V2 calls the intent whenever it can't determine the user utterance for an intent. If there is no response from Amazon Kendra, the conversation continues as configured in the bot.

**Note**  
 Amazon Lex V2 currently does not support the `AMAZON.KendraSearchIntent` during slot elicitation. If Amazon Lex V2 can't determine the user utterance for a slot, it calls the `AMAZON.FallbackIntent`. 

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

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

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

1. If there is no response from Amazon Kendra, Amazon Lex V2 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 V2 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 V2 recognizes, Amazon Lex V2 makes another call to the `Query` operation.

1. If there is no response after the configured number of retries, Amazon Lex V2 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 V2 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 V2 uses the filter in the query request.
+ Add additional query parameters to the request to narrow the search results using your 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 Lambda function. You can create a complete Amazon Kendra query request that Amazon Lex V2 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 V2 sends to Amazon Kendra, you can specify a query in the `kendraQueryRequestPayload`field in your Lambda function. If the query isn't valid, Amazon Lex V2 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
<a name="kendra-search-iam"></a>

To use the `AMAZON.KendraSearchIntent` intent, you must use a role that provides AWS Identity and Access Management (IAM) policies that enable Amazon Lex V2 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 V2 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 V2 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
<a name="kendra-iam-attach"></a>

You can use the console to attach permissions to access the Amazon Kendra `Query` operation to the default Amazon Lex V2 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 V2 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/lexv2.amazonaws.com/AWSServiceRoleForLexBots*"
    },
    {
        "Effect": "Allow",
        "Action": "iam:ListRoles",
        "Resource": "*"
    }
]
}
```

------

### Specifying a Role
<a name="kendra-iam-role"></a>

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 V2 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 V2 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 V2 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
<a name="kendra-search-filter"></a>

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 for your Lex V2 bot](context-mgmt-request-attribs.md). For more information about session attributes, see [Setting session attributes for your Lex V2 bot](context-mgmt-session-attribs.md).

The following is an 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
<a name="kendra-search-response"></a>

Amazon Kendra returns the response to a search in a response from the intent's `IntentClosingSetting` statement. The intent must have a `closingResponse` statement unless a Lambda function produces a closing response message.

Amazon Kendra has five types of responses. 
+ The following two responses require an FAQ to be set up for your Amazon Kendra index. For more details, see [Adding questions and answers directly to a index](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html).
  +  `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. 
+ The following three responses require a data source to be set up for your Amazon Kendra index. For more details, see [Creating a data source](https://docs.aws.amazon.com/kendra/latest/dg/data-source.html). 
  + `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 `closingResponse` 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
<a name="kendra-search-lambda"></a>

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
<a name="kendra-search-lambda-dialog"></a>

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 V2 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 V2 with the `dialogAction` field of the response set to `delegate`. Amazon Lex V2 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
<a name="kendra-search-lambda-fulfillment"></a>

After Amazon Lex V2 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 V2 uses the `closingResponse` statement for responses.

# Example: Creating a FAQ Bot for an Amazon Kendra Index
<a name="faq-bot-kendra-search"></a>

This example creates an Amazon Lex V2 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. Here is a summary of how you will create your FAQ bot using an Amazon Kendra index:

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

1. Create a custom intent. Because the `AMAZON.KendraSearchIntent` and `AMAZON.FallbackIntent` are backup intents, your bot requires at least one other intent that must contain least one utterance. This intent enables your bot to build, but is not used otherwise. Your FAQ bot will therefore contain at least three intents, as in the image below:   
![\[A Kendra FAQ bot with three intents\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/kendra-faqbot/kendra-intents.png)

1. Add the `AMAZON.KendraSearchIntent` intent to your bot and configure it to work with your [Amazon Kendra index](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html). 

1. Test the bot by making a query and verifying that the results from your Amazon Kendra index are documents that answer the query.

**Prerequisites**

Before you can use this example, you need to create an Amazon Kendra index. For more information, see [Getting started with the Amazon Kendra console](https://docs.aws.amazon.com/kendra/latest/dg/gs-console.html) in the *Amazon Kendra Developer Guide*. For this example, choose the sample dataset (**Sample AWS documentation**) as your data source.

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

   1.  For the **Creation method**, choose **Create a blank bot**. 

   1.  In the **Bot configuration** section, give the bot a name that indicates its purpose, such as **KendraTestBot**, and an optional description. The name must be unique in your account. 

   1.  In the **IAM Permissions** section, choose **Create a role with basic Amazon Lex permissions**. This will create an [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) role with the permissions that Amazon Lex V2 needs to run your bot. 

   1.  In the **Children's Online Privacy Protection Act (COPPA)** section, choose **No**. 

   1.  In the **Idle session timeout** and **Advanced settings** sections, leave the default settings and choose **Next**. 

   1.  Now you are in the **Add language to bot** section. In the menu under **Voice interaction**, select **None. This is only a text based application**. Leave the default settings for the remaining fields. 

   1.  Choose **Done**. Amazon Lex V2 creates your bot and a default intent called **NewIntent**, and takes you to the page to configure this intent 

To successfully build a bot, you must create at least one intent that is separate from the `AMAZON.FallbackIntent` and the `AMAZON.KendraSearchIntent`. This intent is required to build your Amazon Lex V2 bot, but isn't used for the FAQ response. This intent must contain at least one sample utterance and the utterance must not apply to any of the questions that your customer asks.

**To create the required intent:**

1.  In the **Intent details** section, give the intent a name, such as **RequiredIntent**. 

1.  In the **Sample utterances** section, type an utterance in the box next to **Add utterance**, such as **Required utterance**. Then choose **Add utterance**. 

1. Choose **Save intent**.

Create the intent to search an Amazon Kendra index and the response message that it should return.

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

1.  Select **Back to intents list** in the navigation pane to return to the **Intents** page for your bot. Choose **Add intent** and select **Use built-in intent** from the dropdown menu. 

1.  In the box that pops up, select the menu under **Built-in intent.** Enter **AMAZON.KendraSearchIntent** in the search bar and then choose it from the list. 

1.  Give the intent a name, such as **KendraSearchIntent**. 

1.  From the **Amazon Kendra index** dropdown menu, choose the index that you want the intent to search. The index that you created in the **Prerequisites** section should be available. 

1.  Select **Add**. 

1. In the intent editor, scroll down to the **Fulfillment** section, select the right arrow to expand the section, and add the following message in the box under **On successful fulfillment**: 

   ```
   I found a link to a document that could help you: ((x-amz-lex:kendra-search-response-document-link-1)).
   ```  
![\[Add the fulfillment response\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/kendra-faqbot/kendra-fulfillment-response.gif)

    For more information about the Amazon Kendra Search Response, see [ Using the Search Response](https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html#kendra-search-response). 

1. Choose **Save intent**, and then choose **Build** to build the bot. When the bot is ready, the banner at the top of the screen turns green and displays a success message. 

Finally, use the console test window to test responses from your bot.

**To test your FAQ bot:**

1.  After the bot is successfully built, choose **Test**. 

1.  Enter **What is Amazon Kendra?** in the console test window. Verify that the bot responds with a link. 

1.  For more information about configuring `AMAZON.KendraSearchIntent`, see [https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html](https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html) and [KendraConfiguration](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_KendraConfiguration.html). 

# AMAZON.PauseIntent
<a name="built-in-intent-pause"></a>

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](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_GetSession.html) operation to retrieve intent data when you resume the current intent.

Common utterances:
+ pause
+ pause that

# AMAZON.QnAIntent
<a name="built-in-intent-qna"></a>

**Note**  
Before you can take advantage of the generative AI features, you must fulfill the following prerequisites  
For information about pricing for using Amazon Bedrock, see [Amazon Bedrock pricing](https://aws.amazon.com/bedrock/pricing/).
Turn on the generative AI capabilities for your bot locale. To do so, follow the steps at [Optimize Lex V2 bot creation and performance by using generative AI](generative-features.md). 

Responds to customer questions by using an Amazon Bedrock FM to search and summarize FAQ responses. This intent is activated when an utterance is not classified into any of the other intents present in the bot. Note that this intent will not be activated for missed utterances when eliciting a slot value. Once recognized, the `AMAZON.QnAIntent`, uses the specified Amazon Bedrock model to search the configured Amazon Bedrock Knowledge Base and respond to the customer question.

**Warning**  
You can't use the `AMAZON.QnAIntent` and the `AMAZON.KendraSearchIntent` in the same bot locale.

The following knowledge store options are available. You must have already created the knowledge store and indexed the documents within it.
+ OpenSearch Service domain – Contains indexed documents. To create a domain, follow the steps at [Creating and managing Amazon OpenSearch Service domains](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/createupdatedomains.html).
+ Amazon Kendra index – Contains indexed FAQ documents. To create a Amazon Kendra index, follow the steps at [Creating an index](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html).
+ Amazon Bedrock Knowledge Base – Contains indexed data sources. To set up a Amazon Bedrock Knowledge Base, follow the steps at [Building a Knowledge Base](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html).

If you select this intent, you configure the following fields and then select **Add** to add the intent.
+ **Bedrock model** – Choose the provider and foundation model to use for this intent. Make sure to check the latest available models and the deprecation schedule and plan migrations accordingly. For more information, see [Model lifecycle](https://docs.aws.amazon.com/bedrock/latest/userguide/model-lifecycle.html#versions-for-eol). 
+ **Knowledge store** – Choose the source from which you want the model pull information from to answer customer questions. The following sources are available.
  + **OpenSearch** – Configure the following fields.
    + **Domain endpoint** – Provide the domain endpoint that you made for the domain or that was provided to you after domain creation.
    + **Index name** – Provide the index to search. For more information, see [Indexing data in Amazon OpenSearch Service](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/indexing.html).
    + Choose how you want to return the response to the customer.
      + **Exact response** – When this option is enabled, the value in the Answer field is used as is for the bot response. The configured Amazon Bedrock foundation model is used to select the exact answer content as-is, without any content synthesis or summarization. Specify the name of the question and answer fields that were configured in the OpenSearch database.
      + **Include fields** – Returns an answer generated by the model using the fields you specify. Specify the name of up to five fields that were configured in the OpenSearch database. Use a semicolon (;) to separate fields.
  + **Amazon Kendra** – Configure the following fields.
    + **Amazon Kendra index** – Select the Amazon Kendra index that you want your bot to search.
    + **Amazon Kendra filter** – To create a filter, select this checkbox. For more information on the Amazon Kendra search filter JSON format, see [Using document attributes to filter search results](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-filtering).
    + **Exact response** – To let your bot return the exact response returned by Amazon Kendra, select this checkbox. Otherwise, the Amazon Bedrock model you select generates a response based on the results.
**Note**  
To use this feature, you must first add FAQ questions to your index by following the steps at [Adding frequently asked questions (FAQs) to an index](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html).
  + **Amazon Bedrock Knowledge Base** – If you choose this option, specify the ID of the Amazon Bedrock Knowledge Base. You can find the ID by checking the details page of the Amazon Bedrock Knowledge Base in the console, or by sending a [GetKnowledgeBase](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetKnowledgeBase.html) request.
    + **Exact response** – When this option is enabled, the value in the Answer field is used as is for the bot response. The configured Amazon Bedrock foundation model is used to select the exact answer content as-is, without any content synthesis or summarization. To use exact response for Amazon Bedrock Knowledge Base you need to do the following:
      + Create individual JSON files with each file containing an answer field that contains the exact response that needs to be returned to end-user.
      + When indexing these documents in Bedrock Knowledge Base, select **Chunking strategy** as **No Chunking**..
      + Define the answer field in Amazon Lex V2, as the Answer field in the Bedrock Knowledge Base.

The responses from the QnAIntent will be stored into the request attributes as shown below:
+ `x-amz-lex:qnA-search-response` – The response from the QnAIntent to the question or utterance.
+ `x-amz-lex:qnA-search-response-source` – Points to the document or list of documents used to generate the response.
+ `x-amz-lex:qna-additional-context` – The additional context used by the QnAIntent to generate the response.

**Additional model configurations**

When AMAZON.QnAIntent is invoked it uses a default prompt template that combines instructions and context with the user query to construct the prompt that’s sent to the model for response generation. You can also provide a custom prompt or update the default prompt to match your requirements.

You can engineer the prompt template with the following tools:

**Prompt placeholders** – Pre-defined variables in AMAZON.QnAIntent for Amazon Bedrock that are dynamically filled in at runtime during the bedrock call. In the system prompt, you can see these placeholders surrounded by the `$` symbol. The following list describes the placeholders you can use:


| Variable | Replaced by | Model | Required? | 
| --- | --- | --- | --- | 
| \$1query\$1results\$1 | The retrieved results for the user query from the Knowledge Store | Selected Bedrock Model | Yes | 
| \$1output\$1instruction\$1 | Underlying instructions for formatting the response generation and citations. Differs by model. If you define your own formatting instructions, we suggest that you remove this placeholder.  | Selected Bedrock Model | No | 
| \$1additional\$1context\$1 | The additional context used by the QnAIntent to generate the response | Selected Bedrock Model | No | 
| \$1locale\$1 | The language in which the bot will answer customer queries | Selected Bedrock Model | No | 

**Default prompt** being used is:

```
$query_results$

$additional_context$

Please only follow the instructions in <instruction> tags below.
<instruction>
Given the conversation history, <additional_context> and <Context>:
(1) first, identify the user query intent and classify it as one of the categories: FAQ_QUERY, OTHER_QUERY, GIBBERISH, GREETINGS, AFFIRMATION, CHITCHAT, or MISC;
(2) second, if the intent is FAQ_QUERY, predict the most relevant grounding passage(s) by providing the passage id(s) or output CANNOTANSWER;
(3) then, generate a concise, to-the-point FAQ-style response in $locale$ locale ONLY USING the grounding content in <Context> and <additional_context>; or output CANNOTANSWER if the user query/request cannot be directly answered with the grounding content. DO NOT mention about the grounding passages such as ids or other meta data; do not create new content not presented in <Context>. Do NOT respond to query that is ill-intented or off-topic;
(4) lastly, provide the confidence level of the above prediction as LOW, MID or HIGH.
</instruction>

$output_instruction$
```

**\$1output\$1instruction\$1** is replaced with:

```
Give your final response in the following form:
<answer>
<intent>FAQ_QUERY or OTHER_QUERY or GIBBERISH or GREETINGS or AFFIRMATION or CHITCHAT or MISC</intent>
<text>a concise FAQ-style response or CANNOTANSWER</text>
<passage_id>passage_id or CANNOTANSWER</passage_id>
<confidence>LOW or MID or HIGH</confidence>
</answer>
```

**Note**  
If you decide not to use the default instructions, then whatever output the LLM provides will be returned as-is back to the end user.  
The output instructions need to contain <text></text> and <passageId></passageId> tags and instructions for the LLM to return the passageIds to provide the response and source attribution.

**Additional context support through session attributes**

You can pass additional context to the `AMAZON.QnAIntent` at runtime through the session attribute `x-amz-lex:qna-additional-context`. This allows you to provide supplementary information that the model can use alongside the knowledge store results when generating a response. The additional context is inserted into the prompt template through the `$additional_context$` placeholder.

**Example:**

```
{"sessionAttributes": {"x-amz-lex:qna-additional-context":"Our support hours are Monday through Friday, 8AM-8PM EST"}}
```

**Amazon Bedrock Knowledge Base metadata filtering support through session attributes**

You can pass the Amazon Bedrock Knowledge Base metadata filters as part of session attribute `x-amz-lex:bkb-retrieval-filter`.

```
             {"sessionAttributes":{"x-amz-lex:bkb-retrieval-filter":"{\"equals\":{\"key\":\"insurancetype\",\"value\":\"farmers\"}}      
```

**Note**  
You need to use the Amazon Bedrock Knowledge Base as the Data store for the QnAIntent to use this filter. For more information, see [https://docs.aws.amazon.com/bedrock/latest/userguide/kb-test-config.html#:~:text=Metadata%20and%20filtering](https://docs.aws.amazon.com/bedrock/latest/userguide/kb-test-config.html#:~:text=Metadata%20and%20filtering)

**Inference configurations**

You can define the inference configurations that will be used when making the call to LLM using session attribute:
+ temperature: type Integer
+ topP
+ maxTokens

**Example:**

```
         {"sessionAttributes":{"x-amz-lex:llm-text-inference-config":"{\"temperature\":0,\"topP\":1,\"maxTokens\":200}"}}      
```

**Bedrock Guardrails support through build-time and session attributes**
+ By using the Console at Buildtime – Provide the GuardrailsIdentifier and the GuardrailsVersion. Learn more under the Additional Model Configurations section.
+ By using Session attributes – You can also define the Guardrails configuration using the session attributes: `x-amz-lex:bedrock-guardrails-identifier` and `x-amz-lex:bedrock-guardrails-version`.

For more information on using Bedrock Guardrails, see [ Guardrails](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html).

# AMAZON.QnAIntent (multiple use support)
<a name="built-in-intent-qna-multi"></a>

You can choose to have multiple AMAZON.QnAIntents within a locale. Amazon Lex V2 support up to 5 AMAZON.QnAIntents within a bot locale. 

AMAZON.QnAIntent can be triggered if one of the following cases is true:
+ If a bot locale contains only 1 AMAZON.QnAIntent and that intent does not contain sample utterances, then it is activated when an utterance is not classified into any of the other intents present in the bot. This intent is activated when an utterance is not classified into any of the other intents present in the bot. Note that this intent will not be activated for missed utterances when eliciting a slot value.
**Note**  
If the response from the FM is unsatisfactory or the call to the FM fails, Amazon Lex V2 then invokes the `AMAZON.FallbackIntent`.
+ If AMAZON.QnAIntent does contain sample utterances, then it is only activated when Amazon Lex V2 recognizes that the user wants to initiate that intent based on user input.
**Note**  
If the response from the FM is unsatisfactory or the call to the FM fails, Amazon Lex V2 invokes the failure next step, defined in the fulfillment block.

**Note**  
If `botLocale` has more than 1 AMAZON.QnAIntent, then each AMAZON.QnAIntent needs to have at least 1 sample utterance.

# AMAZON.QinConnectIntent
<a name="built-in-intent-qinconnect"></a>

**Note**  
To use generative AI capabilities using Amazon Q In Connect, you must complete the following pre-requisites:  
Navigate to the Amazon Connect console and create your instance, if you don't have one already, see [Get started with Amazon Connect](https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-get-started.html).
Enable Amazon Q in Connect for your instance, see [Enable Amazon Q in Connect for your instance](https://docs.aws.amazon.com/connect/latest/adminguide/enable-q.html).

AMAZON.QinConnectIntent responds to customer questions by using the LLM-enhanced evolution of Amazon Connect Wisdom that delivers real-time recommendations to help contact center customers and agents resolve customer issues quickly and accurately. This intent is activated when an utterance is not classified into any of the other intents present in the bot. Note that this intent will not be activated for missed utterances when eliciting a slot value. Once recognized, the AMAZON.QinConnectIntent, uses the specified Q in Connect domain to search the configured Amazon Bedrock Knowledge Base and respond to the customer question. 

**Note**  
You cannot use AMAZON.QinConnectIntent along with AMAZON.QnAIntent in the same bot locale.
If you select another language besides U.S. English, you must customize the self-service prompts (`SELF_SERVICE_PRE_PROCESSING` and `SELF_SERVICE_ANSWER_GENERATION`) to respond in the specified language. For more information on how to customize your prompt, see [Customize Amazon Q in Connect](https://docs.aws.amazon.com/connect/latest/adminguide/customize-q.html#ai-prompts-customize-q).

If you select this intent, you need to configure the following fields and then select **Save Intent** to add the intent to the bot.
+ Amazon Q In Connect Configuration - Provide the Amazon Resource Name (ARN) of the Amazon Q in Connect assistant. Assistant ARN Pattern: `^arn:[a-z-]*?:wisdom:[a-z0-9-]*?:[0-9]{12}:[a-z-]*?/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?:/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}){0,2}$>`.

The responses from the QinConnectIntent will be stored into the request attributes as shown below:
+ `x-amz-lex:q-in-connect-response` – The response from QinConnectIntent to the question or utterance.

**Session Attributes Returned from QinConnectIntent**

Interaction with the QinConnect intent provides additional data about conversation through session attributes. 

1. `x-amz-lex:q-in-connect:session-arn` – An unique identifier for the session created with Amazon Q In Connect during the conversation. 

1. `x-amz-lex:q-in-connect:conversation-status` – The current status of the conversation with QinConnect assistant or domain. There are three values possible for this status:
   + `CLOSED`
   + `READY`
   + `PROCESSING`

1. `x-amz-lex:q-in-connect:conversation-status-reason` – Provides the reason for the current status reported with above attribute. The possible reasons are as follows:
   + `SUCCESS` – Indicates customer has nothing left to ask and question has been answered successfully.
   + `FAILED` – Indicates a failure while answering the customer's question. These are mostly due to failures to understand the customer's question.
   + `REJECTED` – Indicates that the assistant is rejecting to answer customer question, and recommending that the question be handled outside of the bot interaction, such as talking to person or agent, to get more information.

**Note**  
When a bot with QinConnectIntent is invoked during customer interactions driven by an Amazon Connect instance, your session arn needs to be created and passed from the Amazon Connect instance. To create a session, Amazon Connect Flows could be configured with Amazon Q in Connect step.

**Limitations**
+ You cannot use AMAZON.QinConnectIntent along with intents without specific utterances such as AMAZON.QnAIntent, AMAZON.BedrockAgentIntent in the same bot locale.
+ When a bot with QinConnectIntent is invoked during a customer interactions driven by an Amazon Connect instance, your session arn needs to be created and passed from the Amazon Connect instance. To create a session, Amazon Connect Flows could be configured with Amazon Q In Connect step.
+ There can be no more than one AMAZON.QinConnectIntent per bot locale.
+ The Amazon Q in Connect domain used with AMAZON.QinConnectIntent must be in the same AWS Region as the Amazon Lex V2 bot.

**Permissions**

If the QinConnect Intent is used in an Amazon Lex V2 bot, and the bot is using a Service Linked Role (SLR), the Amazon Lex V2 service has the permissions to update the appropriate policies on the role to integrate it with the Q in Connect assistant. If the bot is using a custom IAM role, then the user would need to manually add these permissions to their IAM role.

The Service Linked Role will get updated with the following permissions if the QinConnect intent gets added. A new policy will be added for QinConnect access:

```
{
    "Version": "2012-10-17", 		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Sid": "QInConnectAssistantPolicy",
            "Action": [
                "wisdom:CreateSession",
                "wisdom:GetAssistant"
            ],
            "Resource": [
                "arn:aws:wisdom:*:accountId:assistant/assistantId",
                "arn:aws:wisdom:*:accountId:assistant/assistantId/*"
            ]
        },
        {
            "Effect": "Allow",
            "Sid": "QInConnectSessionsPolicy",
            "Action": [
                "wisdom:SendMessage",
                "wisdom:GetNextMessage"
            ],
            "Resource": [
                "arn:aws:wisdom:*:accountId:session/assistantId/*"
            ]
        },
        {
            "Sid": "QInConnectKmsCMKPolicy",
            "Effect": "Allow",
            "Action": [
                "kms:Decrypt",
                "kms:GenerateDataKey"
            ],
            "Resource": [
                "arn:aws:kms:region:accountId:key/keyId"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceAccount": "accountId",
                    "kms:ViaService": "wisdom.region.amazonaws.com",
                    "kms:EncryptionContext:aws:wisdom:assistant:arn": ["arn:aws:wisdom:region:accountId:assistant/assistantId"]
                }
            }
        }
    ]
}
```

**Note**  
The `QInConnectKmsCMKPolicy` statement is only required if you are using a customer managed KMS key with the Amazon Q in Connect assistant.

**Trust Policy**

```
{
    "Effect": "Allow",
    "Sid": "LexV2InternalTrustPolicy",
    "Principal": {
        "Service": "lexv2.aws.internal"
    },
    "Action": "sts:AssumeRole",
    "Condition": {
        "StringEquals": {
            "aws:SourceAccount": "accountId"
        },
        "ArnLike": {
            "aws:SourceArn": "arn:aws:lex:*:accountId:bot-alias/botId/*"
        }
    }
}
```

# AMAZON.RepeatIntent
<a name="built-in-intent-repeat"></a>

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](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_GetSession.html) operation to get the previous intent information.

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

# AMAZON.ResumeIntent
<a name="built-in-intent-resume"></a>

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
<a name="built-in-intent-start-over"></a>

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
<a name="built-in-intent-stop"></a>

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