

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