

# Integrating an AWS Lambda function into your Amazon Lex V2 bot
Integrating AWS Lambda functions

With [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) functions, you can extend and better control the behavior of your Amazon Lex V2 bot through custom functions that you define. Amazon Lex V2 uses one Lambda function per bot alias per language instead of one Lambda function for each intent. Before you begin, determine which fields in the [input event](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-input-format) you want to draw information from and which fields in the [response](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-response-format) you want to manipulate and return from your Lambda function

To integrate a Lambda function with your Amazon Lex V2 bot, carry out the following steps:

1. [Create a function](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach) in AWS Lambda using your programming language of choice and write up your script.

1. Make sure that the function returns a structure matching the [response format](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-response-format).

1. Deploy the Lambda function.

1. Associate the Lambda function with an Amazon Lex V2 bot alias with the [console](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-console) or [API operations](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-api).

1. Select the conversation stages at which you want to invoke your Lambda function with the [console](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-console) or [API operations](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-api).

1. Build your Amazon Lex V2 bot and test that the Lambda function works as intended. [Debug](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-debug) your function with the help of Amazon CloudWatch.

**Topics**
+ [

# AWS Lambda input event format for Lex V2
](lambda-input-format.md)
+ [

# AWS Lambda response format for Lex V2
](lambda-response-format.md)
+ [

# Common structures in an AWS Lambda function for Amazon Lex V2
](lambda-common-structures.md)
+ [

# Creating an AWS Lambda function for your Amazon Lex V2 bot
](lambda-attach.md)
+ [

# Debugging a Lambda function using CloudWatch Logs logs
](lambda-debug.md)

# AWS Lambda input event format for Lex V2


The first step in integrating a Lambda function into your Amazon Lex V2 bot is to understand the fields in the Amazon Lex V2 event and to determine the information from these fields that you want to use when writing your script. The following JSON object shows the general format of an Amazon Lex V2 event passed to a Lambda function:

**Note**  
The input format may change without a corresponding change to the `messageVersion`. Your code shouldn't throw an error if new fields are present.

```
{
    "messageVersion": "1.0",
    "invocationSource": "DialogCodeHook | FulfillmentCodeHook",
    "inputMode": "DTMF | Speech | Text",
    "responseContentType": "audio/mpeg | audio/ogg | audio/pcm | text/plain; charset=utf-8",
    "sessionId": string,
    "inputTranscript": string,
    "invocationLabel": string,
    "bot": {
        "id": string,
        "name": string,
        "localeId": string,
        "version": string,
        "aliasId": string,
        "aliasName": string
    },
    "interpretations": [
        {
            "interpretationSource": "Bedrock | Lex",
            "intent": {
                // see Intent for details about the structure
            },
            "nluConfidence": number,
            "sentimentResponse": {
                "sentiment": "MIXED | NEGATIVE | NEUTRAL | POSITIVE",
                "sentimentScore": {
                    "mixed": number,
                    "negative": number,
                    "neutral": number,
                    "positive": number
                }
            }
        },
        ...
    ],
    "proposedNextState": {
        "dialogAction": {
            "slotToElicit": string,
            "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot"
        },
        "intent": {
            // see Intent for details about the structure
        },
        "prompt": {
            "attempt": string 
        }
    },
    "requestAttributes": {
        string: string,
        ...
    },
    "sessionState": {
        // see Session state for details about the structure
    },
    "transcriptions": [
        {
            "transcription": string,
            "transcriptionConfidence": number,
            "resolvedContext": {
                "intent": string
            },
            "resolvedSlots": {
                slot name: {
                    // see Slots for details about the structure
                },
                ...
            }
        },
        ...
    ]
}
```

Each field in the input event is described below:

## messageVersion


The version of the message that identifies the format of the event data going into the Lambda function and the expected format of the response from a Lambda function.

**Note**  
You configure this value when you define an intent. In the current implementation, Amazon Lex V2 only supports message version 1.0. Therefore, the console assumes the default value of 1.0 and doesn't show the message version.

## invocationSource


The code hook that called the Lambda function. The following values are possible:

`DialogCodeHook` – Amazon Lex V2 called the Lambda function after input from the user.

`FulfillmentCodeHook` – Amazon Lex V2 called the Lambda function after filling all the required slots and the intent is ready for fulfillment.

## inputMode


The mode of the user utterance. The possible values are as follows:

`DTMF` – The user input the utterance using a touch-tone keypad (Dual Tone Multi-Frequency).

`Speech` – The user spoke the utterance.

`Text` – The user typed the utterance.

## responseContentType


The mode of the bot's response to the user. `text/plain; charset=utf-8` indicates that the last utterance was written, while a value beginning with `audio` indicates that the last utterance was spoken.

## sessionId


The alphanumeric session identifier used for the conversation.

## inputTranscript


A transcription of the input from the user.
+ For text input, this is the text that the user typed. For DTMF input, this is the key that the user input.
+ For speech input, this is the text to which Amazon Lex V2 converts the user utterance in order to invoke an intent or fill a slot.

## invocationLabel


A value that indicates the response that invoked the Lambda function. You can set invocation labels for the initial response, slots, and confirmation response.

## bot


Information about the bot that processed the request, consisting of the following fields:
+ **id** – The identifier assigned to the bot when you created it. You can see the bot ID in the Amazon Lex V2 console on the bot **Settings** page.
+ **name** – The name that you gave the bot when you created it.
+ **localeId** – The identifier of the locale that you used for your bot. For a list of locales, see [Languages and locales supported by Amazon Lex V2](how-languages.md).
+ **version** – The version of the bot that processed the request.
+ **aliasId** – The identifier assigned to the bot alias when you created it. You can see the bot alias ID in the Amazon Lex V2 console on the **Aliases** page. If you can't see the alias ID in the list, choose the gear icon on the upper right and turn on **Alias ID**.
+ **aliasName** – The name that you gave the bot alias.

## interpretations


A list of information about intents that Amazon Lex V2 considers possible matches to the user's utterance. Each item is a structure that provides information about the utterance's match to an intent, with the following format:

```
{
    "intent": {
        // see Intent for details about the structure
    },
    "interpretationSource": "Bedrock | Lex",
    "nluConfidence": number,
    "sentimentResponse": {
        "sentiment": "MIXED | NEGATIVE | NEUTRAL | POSITIVE",
        "sentimentScore": {
            "mixed": number,
            "negative": number,
            "neutral": number,
            "positive": number
        }
    }
}
```

The fields within the structure are as follows:
+ **intent** – A structure containing information about the intent. See [Intent](lambda-common-structures.md#lambda-intent) for details about the structure.
+ **nluConfidence** – A score that indicates how confident Amazon Lex V2 is that the intent matches the user's intent.
+ **sentimentResponse** – An analysis of the sentiment of the response, containing the following fields:
  + **sentiment** – Indicates whether the sentiment of the utterance is `POSITIVE`, `NEGATIVE`, `NEUTRAL`, or `MIXED`.
  + **sentimentScore** – A structure mapping each sentiment to a number indicating how confident Amazon Lex V2 is that the utterance conveys that sentiment.
+ **interpretationSource** – Indicates whether a slot is resolved by Amazon Lex V2 or Amazon Bedrock.

## proposedNextState


If the Lambda function sets the `dialogAction` of the `sessionState` to `Delegate`, this field appears and shows Amazon Lex V2's proposal for the next step in the conversation. Otherwise, the next state depends on the settings that you return in the response from your Lambda function. This structure is only present if both of the following statements are true:

1. The `invocationSource` value is `DialogCodeHook`

1. The predicted `type` of `dialogAction` is `ElicitSlot`.

You can use this information to add `runtimeHints` at the right point in the conversation. See [Improving recognition of slot values with runtime hints in the conversation](using-hints.md) for more information. `proposedNextState` is a structure containing the following fields:

The structure of `proposedNextState` is as follows:

```
"proposedNextState": {
    "dialogAction": {
        "slotToElicit": string,
        "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot"
    },
    "intent": {
        // see Intent for details about the structure
    },
    "prompt": {
        "attempt": string 
    }
}
```
+ **dialogAction** – Contains information about the next step that Amazon Lex V2 proposes. The fields in the structure are as follows: 
  + **slotToElicit** – The slot to elicit next as proposed by Amazon Lex V2. This field only appears if the `type` is `ElicitSlot`.
  + **type** – The next step in the conversation as proposed by Amazon Lex V2. The following values are possible:

    `Delegate` – Amazon Lex V2 determines the next action.

    `ElicitIntent` – The next action is to elicit an intent from the user.

    `ElicitSlot` – The next action is to elicit a slot value from the user.

    `Close` – Ends the intent fulfillment process and indicates that there will not be a response from the user.

    `ConfirmIntent` – The next action is to ask the user if the slots are correct and the intent is ready for fulfillment.
+ **intent** – The intent that the bot has determined that the user is trying to fulfill. See [Intent](lambda-common-structures.md#lambda-intent) for details about the structure.
+ **prompt** – A structure containing the field `attempt`, which maps to a value that specifies how many times Amazon Lex V2 has prompted the user for the next slot. The possible values are `Initial` for the first attempt and `Retry1`, `Retry2`, `Retry3`, `Retry4`, and `Retry5` for subsequent attempts. 

## requestAttributes


A structure containing request-specific attributes that the client sends in the request. Use request attributes to pass information that doesn't need to persist for the entire session. If there are no request attributes, the value will be null. For more information, see [Setting request attributes for your Lex V2 bot](context-mgmt-request-attribs.md).

## sessionState


The current state of the conversation between the user and your Amazon Lex V2 bot. See [Session state](lambda-common-structures.md#lambda-session-state) for details about the structure.

## transcriptions


A list of transcriptions that Amazon Lex V2 considers possible matches to the user's utterance. For more information, see [Using voice transcription confidence scores to improve conversations with your Lex V2 bot](using-transcript-confidence-scores.md). Each item is an object with the following format, containing information about one possible transcription:

```
{
    "transcription": string,
    "transcriptionConfidence": number,
    "resolvedContext": {
        "intent": string
    },
    "resolvedSlots": {
        slot name: {
            // see Slots for details about the structure
        },
        ...
    }
}
```

The fields are described below:
+ **transcription** – A transcription that Amazon Lex V2 considers a possible match to the user's audio utterance.
+ **transcriptionConfidence** – A score that indicates how confident Amazon Lex V2 is that the intent matches the user's intent.
+ **resolvedContext** – A structure containing the field `intent`, which maps to the intent to which the utterance pertains.
+ **resolvedSlots** – A structure whose keys are the names of each slot that is resolved by the utterance. Each slot name maps to a structure containing information about that slot. See [Slots](lambda-common-structures.md#lambda-slot) for details about the structure.

# AWS Lambda response format for Lex V2


The second step in integrating a Lambda function into your Amazon Lex V2 bot is to understand the fields in the Lambda function response and to determine which parameters you want to manipulate. The following JSON object shows the general format of an Lambda response that is returned to Amazon Lex V2:

```
{
    "sessionState": {
        // see Session state for details about the structure
    },
    "messages": [
        {
            "contentType": "CustomPayload | ImageResponseCard | PlainText | SSML",
            "content": string,
            "imageResponseCard": {
                "title": string,
                "subtitle": string,
                "imageUrl": string,
                "buttons": [
                    {
                        "text": string,
                        "value": string
                    },
                    ...
                ]
            }
        },
        ...
    ],
    "requestAttributes": {
        string: string,
        ...
    }
}
```

Each field in the response is described below:

## sessionState


The state of the conversation between the user and your Amazon Lex V2 bot that you want to return. See [Session state](lambda-common-structures.md#lambda-session-state) for details about the structure. This field is always required.

## messages


A list of messages that Amazon Lex V2 returns to the customer for the next turn of the conversation. If the `contentType` you provide is `PlainText`, `CustomPayload`, or `SSML`, write the message you want to return to the customer in the `content` field. If the `contentType` you provide is `ImageResponseCard`, give the details of the card in the `imageResponseCard` field. If you don't supply messages, Amazon Lex V2 uses the appropriate message defined when the bot was created.

The `messages` field is required if the `dialogAction.type` is `ElicitIntent` or `ConfirmIntent`.

Each item in the list is a structure in the following format, containing information about a message to return to the user. Here is an example:

```
{
    "contentType": "CustomPayload | ImageResponseCard | PlainText | SSML",
    "content": string,
    "imageResponseCard": {
        "title": string,
        "subtitle": string,
        "imageUrl": string,
        "buttons": [
            {
                "text": string,
                "value": string
            },
            ...
        ]
    }
}
```

A description for each field is provided below:
+ **contentType** – The type of message to use.

  `CustomPayload` – A response string that you can customize to include data or metadata for your application.

  `ImageResponseCard` – An image with buttons that the customer can select. See [ImageResponseCard](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_ImageResponseCard.html) for more information.

  `PlainText` – A plain text string.

  `SSML` – A string that includes Speech Synthesis Markup Language to customize the audio response.
+ **content** – The message to send to the user. Use this field if the message type is `PlainText`, `CustomPayload`, or `SSML`.
+ **imageResponseCard** – Contains the definition of the response card to show to the user. Use this field if the message type is `ImageResponseCard`. Maps to a structure containing the following fields:
  + **title** – The title of the response card.
  + **subtitle** – The prompt for the user to choose a button.
  + **imageUrl** – A link to an image for the card.
  + **buttons** – A list of structures containing information about a button. Each structure contains a `text` field with the text to display and a `value` field with the value to send to Amazon Lex V2 if the customer selects that button. You can include up to three buttons.

## requestAttributes


A structure containing request-specific attributes for the response to the customer. See [Setting request attributes for your Lex V2 bot](context-mgmt-request-attribs.md) for more information. This field is optional.

## Required fields in the response


Minimally, the Lambda response must include a `sessionState` object. Within that, provide a `dialogAction` object and specify the `type` field. Depending on the `type` of `dialogAction` that you provide, there may be other required fields for the Lambda response. These requirements are described as follows, alongside minimal working examples:

### Delegate


**Delegate** lets Amazon Lex V2 determine the next step. No other fields are required.

```
{
    "sessionState": {
        "dialogAction": {
            "type": "Delegate"
    }
}
```

### ElicitIntent


**ElicitIntent** prompts the customer to express an intent. You must include at least one message in the `messages` field to prompt elicitation of an intent.

```
{
    "sessionState": {
        "dialogAction": {
            "type": "ElicitIntent"
    },
    "messages": [
        {
            "contentType": PlainText,
            "content": "How can I help you?"
        }
    ]
}
```

### ElicitSlot


**ElicitSlot** prompts the customer to provide a slot value. You must include the name of the slot in the `slotToElicit` field in the `dialogAction` object. You must also include the `name` of the `intent` in the `sessionState` object.

```
{`
    "sessionState": {
        "dialogAction": {
            "slotToElicit": "OriginCity",
            "type": "ElicitSlot"
        },
        "intent": {
            "name": "BookFlight"
        }
    }
}
```

### ConfirmIntent


**ConfirmIntent** confirms the customer's slot values and whether the intent is ready to be fulfilled. You must include the `name` of the `intent` in the `sessionState` object and the `slots` to be confirmed. You must also include at least one message in the `messages` field to ask the user for confirmation of the slot values. Your message should prompt a "yes" or "no" response. If the user responds "yes", Amazon Lex V2 sets the `confirmationState` of the intent to `Confirmed`. If the user responds "no", Amazon Lex V2 sets the `confirmationState` of the intent to `Denied`.

```
{
    "sessionState": {
        "dialogAction": {
            "type": "ConfirmIntent"
        },
        "intent": {
            "name": "BookFlight",
            "slots": {
                "DepartureDate": {
                    "value": {
                        "originalValue": "tomorrow",
                        "interpretedValue": "2023-05-09",
                        "resolvedValues": [
                            "2023-05-09"
                    ]
                 }
                },
                "DestinationCity": {
                    "value": {
                        "originalValue": "sf",
                        "interpretedValue": "sf",
                        "resolvedValues": [
                            "sf"
                        ]
                    }
                },
                "OriginCity": {
                    "value": {
                        "originalValue": "nyc",
                        "interpretedValue": "nyc",
                        "resolvedValues": [
                            "nyc"
                        ]
                    }
                }
            }
        }
    },
    "messages": [
        {
            "contentType": PlainText,
            "content": "Okay, you want to fly from {OriginCity} to \
            {DestinationCity} on {DepartureDate}. Is that correct?"
        }
    ]
}
```

### Close


**Close** ends the fulfillment process of the intent and indicates that no further responses are expected from the user. You must include the `name` and `state` of the `intent` in the `sessionState` object. The compatible intent states are `Failed`, `Fulfilled`, and `InProgress`.

```
"sessionState": {
    "dialogAction": {
        "type": "Close"
    },
    "intent": {
        "name": "BookFlight",
        "state": "Failed | Fulfilled | InProgress"
    }
}
```

# Common structures in an AWS Lambda function for Amazon Lex V2
Common structures

Within the Lambda response, there are a number of structures that recur. Details about these common structures are provided in this section.

## Intent


```
"intent": {
    "confirmationState": "Confirmed | Denied | None",
    "name": string,
    "slots": {
        // see Slots for details about the structure
    },
    "state": "Failed | Fulfilled | FulfillmentInProgress | InProgress | ReadyForFulfillment | Waiting",
    "kendraResponse": {
        // Only present when intent is KendraSearchIntent. For details, see
// https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax       }
}
```

The `intent` field is mapped to an object with the following fields:

### confirmationState


Indicates whether the user has confirmed the slots for the intent and the intent is ready for fulfillment. The following values are possible:

`Confirmed` – The user confirms that the slot values are correct.

`Denied` – The user indicates that the slot values are incorrect.

`None` – The user has not reached the confirmation stage yet.

### name


The name of the intent.

### slots


Information about the slots required to fulfill the intent. See [Slots](#lambda-slot) for details about the structure.

### state


Indicates the fulfillment state for the intent. The following values are possible:

`Failed` – The bot failed to fulfill the intent.

`Fulfilled` – The bot has completed fulfillment of the intent.

`FulfillmentInProgress` – The bot is in the middle of fulfilling the intent.

`InProgress` – The bot is in the middle of eliciting the slot values that are necessary to fulfill the intent.

`ReadyForFulfillment` – The bot has elicited all the slot values for the intent and is ready to fulfill the intent.

`Waiting` – The bot is waiting for a response from the user (limited to streaming conversations).

### kendraResponse


Contains information about the results of the Kendra search query. This field only appears if the intent is a `KendraSearchIntent`. See [the response syntax in the Query API call for Kendra](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax) for more information.

## Slots


The `slots` field exists within an `intent` structure and is mapped to a structure whose keys are the names of the slots for that intent. If the slot is not a multi-valued slot (see [Using multiple values in a slot](multi-valued-slots.md) for more details), it is mapped to a structure with the following format. Note that the `shape` is `Scalar`.

```
{
    slot name: {
        "shape": "Scalar",
        "value": {
            "originalValue": string,
            "interpretedValue": string,
            "resolvedValues": [
                string,
                ...
            ]
        }
    }
}
```

If the slot is a multi-valued slot, the object to which it is mapped contains another field called `values`, which is mapped to a list of structures, each containing information about a slot that makes up the multi-valued slot. The format of each object in the list matches that of the object to which a regular slot is mapped. Note that the `shape` is `List`, but the `shape` of the component slots under `values` is `Scalar`.

```
{
    slot name: {
    "shape": "List",
    "value": {
        "originalValue": string,
        "interpretedValue": string,
        "resolvedValues": [
            string,
            ...
        ]
    },
    "values": [
        {
            "shape": "Scalar",
            "value": {
                "originalValue": string,
                "interpretedValue": string,
                "resolvedValues": [
                    string,
                    ...
                ]
            }
        },
        {
            "shape": "Scalar",
            "value": {
                "originalValue": string,
                "interpretedValue": string,
                "resolvedValues": [
                    string,
                    ...
                ]
            }
        },
        ...
    ]
}
```

The fields in the slot object are described below:

### shape


The shape of the slot. This value is `List` if there are multiple values in the slot (see [Using multiple values in a slot](multi-valued-slots.md) for more details) and is `Scalar` otherwise.

### value


An object containing information about the value that the user provided for a slot and Amazon Lex V2's interpretation, in the following format:

```
{
    "originalValue": string,
    "interpretedValue": string,
    "resolvedValues": [
        string,
        ...
    ]
}
```

The fields are described below:
+ **originalValue** – The part of the user's response to the slot elicitation that Amazon Lex V2 determines is relevant to the slot value.
+ **interpretedValue** – The value that Amazon Lex V2 determines for the slot, given the user input.
+ **resolvedValues** – A list of values that Amazon Lex V2 determines are possible resolutions for the user input.

### values


A list of objects containing information about the slots that make up the multi-value slot. The format of each object matches that of a normal slot, with the `shape` and `value` fields described above. `values` only appears if the slot consists of multiple values (see [Using multiple values in a slot](multi-valued-slots.md) for more details). The following JSON object shows two component slots:

```
"values": [
    {
        "shape": "Scalar",
        "value": {
            "originalValue": string,
            "interpretedValue": string,
            "resolvedValues": [
                string,
                ...
            ]
        }
    },
    {
        "shape": "Scalar",
        "value": {
            "originalValue": string,
            "interpretedValue": string,
            "resolvedValues": [
                string,
                ...
            ]
        }
    },
    ...
]
```

## Session state


The `sessionState` field is mapped to an object containing information about the state of the conversation with the user. The actual fields that appear in the object depend on the type of dialog action. See [Required fields in the response](lambda-response-format.md#lambda-response-required) for the required fields in a Lambda response. The format of the `sessionState` object is as follows:

```
"sessionState": {
    "activeContexts": [
        {
            "name": string,
            "contextAttributes": {
                string: string
            },
            "timeToLive": {
                "timeToLiveInSeconds": number,
                "turnsToLive": number
            }
        },
        ...
    ],
    "sessionAttributes": {
        string: string,
        ...
    },
    "runtimeHints": {
        "slotHints": {
            intent name: {
                slot name: {
                    "runtimeHintValues": [
                        {
                            "phrase": string
                        },
                        ...
                    ]
                },
                ...
            },
            ...
        }
    },
    "dialogAction": {
        "slotElicitationStyle": "Default | SpellByLetter | SpellByWord",
        "slotToElicit": string,
        "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot"
    },
    "intent": {
        // see Intent for details about the structure
    },
    "originatingRequestId": string
}
```

The fields are described below:

### activeContexts


A list of objects containing information about a context that a user is using in a session. Use contexts to facilitate and control intent recognition. For more information about contexts, see [Setting intent context for your Lex V2 bot](context-mgmt-active-context.md). Each object is formatted as follows:

```
{
    "name": string,
    "contextAttributes": {
        string: string
    },
    "timeToLive": {
        "timeToLiveInSeconds": number,
        "turnsToLive": number
    }
}
```

The fields are described below:
+ **name** – The name of the context.
+ **contextAttributes** – An object containing the names of attributes for the context and the values that they are mapped to.
+ **timeToLive** – An object that specifies how long the context remains active. This object can contain one or both of the following fields:
  + **timeToLiveInSeconds** – The number of seconds that the context remains active.
  + **turnsToLive** – The number of turns that the context remains active.

### sessionAttributes


A map of key/value pairs representing session-specific context information. For more information, see [Setting session attributes for your Lex V2 bot](context-mgmt-session-attribs.md). The object is formatted as follows:

```
{
    string: string,
    ...
}
```

### runtimeHints


Provides hints to the phrases that a customer is likely to use for a slot in order to improve audio recognition. The values that you provide in the hints boost audio recognition of those values over similar-sounding words. The format of the `runtimeHints` object is as follows:

```
{
    "slotHints": {
        intent name: {
            slot name: {
                "runtimeHintValues": [
                    {
                        "phrase": string
                    },
                    ...
                ]
            },
            ...
        },
        ...
    }
}
```

The `slotHints` field maps to an object whose fields are the names of the intents in the bot. Each intent name maps to an object whose fields are the names of the slots for that intent. Each slot name maps to a structure with a single field, `runtimeHintValues`, which is a list of objects. Each object contains a `phrase` field that maps to a hint.

### dialogAction


Determines the next action for Amazon Lex V2 to take. The format of the object is as follows:

```
{
    "slotElicitationStyle": "Default | SpellByLetter | SpellByWord",
    "slotToElicit": string,
    "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot"
}
```

The fields are described below:
+  **slotElicitationStyle** – Determines how Amazon Lex V2 interprets audio input from the user if the `type` of `dialogAction` is `ElicitSlot`. For more information, see [Capturing slot values with spelling styles during the conversation](spelling-styles.md). The following values are possible:

  `Default` – Amazon Lex V2 interprets the audio input in the default manner to fulfill a slot.

  `SpellByLetter` – Amazon Lex V2 listens for the user's spelling of the slot value.

  `SpellByWord` – Amazon Lex V2 listens for the user's spelling of the slot value using words associated with each letter (for example, "a as in apple").
+  **slotToElicit** – Defines the slot to elicit from the user if the `type` of `dialogAction` is `ElicitSlot`. 
+ **type** – Defines the action that the bot should execute. The following values are possible:

  `Delegate` – Lets Amazon Lex V2 determine the next step.

  `ElicitIntent` – Prompts the customer to express an intent.

  `ConfirmIntent` – Confirms the customer's slot values and whether the intent is ready for fulfillment.

  `ElicitSlot` – Prompts the customer to provide a slot value for an intent.

  `Close` – Ends the intent fulfillment process.

### intent


See [Intent](#lambda-intent) for the structure of the `intent` field.

### originatingRequestId


A unique identifier for the request. This field is optional for the Lambda response.

# Creating an AWS Lambda function for your Amazon Lex V2 bot
Creating and attaching a Lambda function to a bot alias

To create a Lambda function for your Amazon Lex V2 bot, access AWS Lambda from your AWS Management Console and create a new function. You can refer to the [AWS Lambda developer guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) for more details about AWS Lambda.

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

1. Choose **Functions** in the left sidebar.

1. Select **Create function**.

1. You can select **Author from scratch** to start with minimal code, **Use a blueprint** to select sample code for common use cases from a list, or **Container image** to select a container image to deploy for your function. If you select **Author from scratch**, continue with the following steps:

   1. Give your function a meaningful **Function name** to describe what it does.

   1. Choose a language from the drop down menu under **Runtime** to write your function in.

   1. Select an instruction set **Architecture** for your function.

   1. By default, Lambda creates a role with basic permissions. To use an existing role or to create a role using AWS policy templates, expand the **Change default execution role** menu and select an option.

   1. Expand the **Advanced settings** menu to configure more options.

1. Select **Create function**.

The following image shows what you see when you create a new function from scratch:

![\[A new Lambda function.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/lambda/lambda-new-function.png)


The Lambda handler function differs depending on the language you use. It minimally takes an `event` JSON object as an argument. You can see the fields in the `event` that Amazon Lex V2 provides at [AWS Lambda input event format for Lex V2](lambda-input-format.md). Modify the handler function to ultimately return a `response` JSON object that matches the format described in [AWS Lambda response format for Lex V2](lambda-response-format.md).
+ Once you finish writing your function, select **Deploy** to allow the function to be used.

Remember that you can associate each bot alias with at most one Lambda function. However, you can define as many functions as you need for your bot within the Lambda code and call these functions in the Lambda handler function. For example, while all intents in the same bot alias must call the same Lambda function, you can create a router function that activates a separate function for each intent. The following is a sample router function that you can use or modify for your application:

```
import os
import json
import boto3

# reuse client connection as global
client = boto3.client('lambda')

def router(event):
    intent_name = event['sessionState']['intent']['name']
    fn_name = os.environ.get(intent_name)
    print(f"Intent: {intent_name} -> Lambda: {fn_name}")
    if (fn_name):
        # invoke lambda and return result
        invoke_response = client.invoke(FunctionName=fn_name, Payload = json.dumps(event))
        print(invoke_response)
        payload = json.load(invoke_response['Payload'])
        return payload
    raise Exception('No environment variable for intent: ' + intent_name)

def lambda_handler(event, context):
    print(event)
    response = router(event)
    return response
```

**When to use AWS Lambda functions in Amazon Lex V2 bot conversations**

You can use Lambda functions at the following points in a conversation with a user:
+ In the initial response after the intent is recognized. For example, after the user says they want to order a pizza.
+ After eliciting a slot value from the user. For example, after the user tells the bot the size of pizza they want to order.
+ Between each retry for eliciting a slot. For example, if the customer doesn't use a recognized pizza size.
+ When confirming an intent. For example, when confirming a pizza order.
+ To fulfill an intent. For example, to place an order for a pizza.
+ After fulfillment of the intent, and before your bot closes the conversation. For example, to switch to an intent to order a drink.

**Topics**
+ [

# Attach an AWS Lambda function to a Amazon Lex V2 bot using the console
](lambda-attach-console.md)
+ [

# Attach an AWS Lambda function to a Amazon Lex V2 bot using API operations
](lambda-attach-api.md)

# Attach an AWS Lambda function to a Amazon Lex V2 bot using the console


You must first attach a Lambda function to your Amazon Lex V2 bot alias before you can invoke it. You can only attach one Lambda function with each bot alias. Perform these steps to attach the Lambda function using the AWS console. 

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 **Bots** from the left side panel and from the list of bots, choose the name of the bot that you want to attach a Lambda function to.

1. From the left side panel, select **Aliases** under the **Deployment** menu.

1. From the list of aliases, choose the name of the alias that you want to attach a Lambda function to.

1. In the **Languages** panel, select the language that you want a Lambda function to. Select **Manage languages in alias** to add a language if it is not present in the panel.

1. In the **Source** dropdown menu, choose the name of the Lambda function that you want to attach.

1. In the **Lambda function version or alias** dropdown menu, choose the version or alias of the Lambda function that you want to use. Then select **Save**. The same Lambda function is used for all intents in a language supported by the bot.

**Setting a Amazon Lex V2 intent to invoke a Lambda function using the console**

1. After selecting a bot, select **Intents** in the left side menu under the language of the bot for which you want to invoke the Lambda function.

1. Choose the intent in which you want to invoke the Lambda function to open the intent editor.

1. There are two options for setting the Lambda code hook:

   1. To invoke the Lambda function after every step of the conversation, scroll to the **Code hooks** section at the bottom of the intent editor and select the **Use a Lambda function for initialization and validation** check box, as in the following image:  
![\[The code hooks section of the Amazon Lex V2 intent editor.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/lambda/lambda-code-hooks-all.png)

   1. Alternatively, use the **Dialog code hook** section in the conversation stages at which to invoke the Lambda function. The **Dialog code hook** section appears as follows:  
![\[The code hooks section of the Amazon Lex V2 intent editor.\]](http://docs.aws.amazon.com/lexv2/latest/dg/images/lambda/lambda-code-hook-step.png)

      There are two ways to control how Amazon Lex V2 calls the code hook for a response:
      + Toggle the **Active** button to mark it as *active* or *inactive*. When a code hook is *active*, Amazon Lex V2 will call the code hook. When the code hook is *inactive*, Amazon Lex V2 does not run the code hook.
      + Expand the **Lambda dialog code hook** section and select the **Invoke Lambda function** check box to mark it as *enabled* or *disabled*. You can only enable or disable a code hook when it is marked active. When it is marked *enabled*, the code hook is run normally. When it is *disabled*, the code hook is not called and Amazon Lex V2 acts as if the code hook returned successfully. To configure responses after the dialog code hook succeeds, fails, or times out, select **Advanced options**

      The Lambda code hook can be invoked at the following conversation stages:
      + To invoke the function as the **initial response**, scroll to the **Initial Response** section, expand the arrow next to **Response to acknowledge the user's request**, and select **Advanced options**. Find the **Dialog code hook** section at the bottom of the menu that pops up.
      + To invoke the function after **slot elicitation**, scroll to the **Slots** section, expand the arrow next to the relevant **Prompt for slot**, and select **Advanced options**. Find the **Dialog code hook** section near the bottom of the menu that pops up, just above **Default values**.

        You can also invoke the function after each elicitation. To do this, expand **Bot elicits information** in the **Slot prompts** section, select **More prompt options**, and select the check box next to **Invoke Lambda code hook after each elicitation**.
      + To invoke the function for **intent confirmation**, scroll to the **Confirmation** section, expand the arrow next to **Prompts to confirm the intent**, and select **Advanced options**. Find the **Dialog code hook** section at the bottom of the menu that pops up.
      + To invoke the function for **intent fulfillment**, scroll to the **Fulfillment** section. Toggle the **Active** button to set the code hook to *active*. Expand the arrow next to **On successful fulfillment**, and select **Advanced options**. Select the check box next to **Use a Lambda function for fulfillment** under the **Fulfillment Lambda code hook** section to set the code hook to *enabled*.

1. Once you set the conversation stages at which to invoke the Lambda function, **Build** the bot again to test the function.

# Attach an AWS Lambda function to a Amazon Lex V2 bot using API operations


You must first attach a Lambda function to your Amazon Lex V2 bot alias before you can invoke it. You can only associate one Lambda function with each bot alias. Perform these steps to attach the Lambda function using API operations. 

If you are creating a new bot alias, use the [CreateBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateBotAlias.html) operation to attach a Lambda function. To attach a Lambda function to an existing bot alias, use the [UpdateBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateBotAlias.html) operation. Modify the `botAliasLocaleSettings` field to contain the correct settings:

```
{
    "botAliasLocaleSettings" : {
        locale: {
            "codeHookSpecification": {
                "lambdaCodeHook": {
                    "codeHookInterfaceVersion": "1.0",
                    "lambdaARN": "arn:aws:lambda:region:account-id:function:function-name"
                }
            },
            "enabled": true
        },
        ...
    }
}
```

1. The `botAliasLocaleSettings` field maps to an object whose keys are the locales in which you want to attach the Lambda function. See [Supported languages and locales](how-languages.md#supported-languages) for a list of supported locales and the codes that are valid keys.

1. To find the `lambdaARN` for a Lambda function, open the AWS Lambda console at [https://console.aws.amazon.com/lambda/home](https://console.aws.amazon.com/lambda/home), select **Functions** in the left sidebar, and select the function to associate with the bot alias. On the right side of the **Function overview**, find the `lambdaARN` under **Function ARN**. It should contain a region, account ID, and the name of the function.

1. To allow Amazon Lex V2 to invoke the Lambda function for the alias, set the `enabled` field to `true`.

**Setting a Amazon Lex V2 intent to invoke a Lambda function using API operations**

To set up the Lambda function invocation during an intent, use the [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) operation if you are creating a new intent, or the [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) operation if you are invoking the function in an existing intent. The fields that control the Lambda function invocation in the intent operations are `dialogCodeHook`, `initialResponseSetting`, `intentConfirmationSetting`, and `fulfillmentCodeHook`.

If you invoke the function during the elicitation of a slot, use the [CreateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateSlot.html) operation if you are creating a new slot, or the [UpdateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateSlot.html) operation to invoke the function in an existing slot. The field that controls the Lambda function invocation in the slot operations is the `slotCaptureSetting` of the `valueElicitationSetting` object.

1. To set the Lambda dialog code hook to run after every turn of the conversation, set the `enabled` field of the following [DialogCodeHookSettings](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogCodeHookSettings.html) object in the `dialogCodeHook` field to `true`:

   ```
   "dialogCodeHook": {
       "enabled": boolean
   }
   ```

1. Alternatively, you can set the Lambda dialog code hook to run only at specific points in the conversations by modifying the `codeHook` and/or `elicitationCodeHook` field within the structures that correspond to the conversation stages at which you want to invoke the function. To use the Lambda dialog code hook for intent fulfillment, use the `fulfillmentCodeHook` field in 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) operation. The structures and uses of these three types of code hooks are as follows:

## codeHook


The `codeHook` field defines the settings for the code hook to run at a given stage in the conversation. It is a [DialogCodeHookInvocationSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogCodeHookInvocationSetting.html) object with the following structure:

```
"codeHook": {
    "active": boolean,
    "enableCodeHookInvocation": boolean,
    "invocationLabel": string,
    "postCodeHookSpecification": [PostDialogCodeHookInvocationSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostDialogCodeHookInvocationSpecification.html),
}
```
+ Change the `active` field to `true` for Amazon Lex V2 to call the code hook at that point in the conversation.
+ Change the `enableCodeHookInvocation` field to `true` for Amazon Lex V2 to allow the code hook to run normally. If you mark it `false`, Amazon Lex V2 acts as if the code hook returned successfully.
+ The `invocationLabel` indicates the dialog step from which the code hook is invoked.
+ Use the `postCodeHookSpecification` field to specify the actions and messages that occur after the code hook succeeds, fails, or times out.

## elicitationCodeHook


The `elicitationCodeHook` field defines the settings for the code hook to run in the event that a slot or slots need to be re-elicited. This scenario may occur if slot elicitation fails or intent confirmation is denied. The `elicitationCodeHook` field is an [ElicitationCodeHookInvocationSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ElicitationCodeHookInvocationSetting.html) object with the following structure:

```
"elicitationCodeHook": {
    "enableCodeHookInvocation": boolean,
    "invocationLabel": string
}
```
+ Change the `enableCodeHookInvocation` field to `true` for Amazon Lex V2 to allow the code hook to run normally. If you mark it `false`, Amazon Lex V2 acts as if the code hook returned successfully.
+ The `invocationLabel` indicates the dialog step from which the code hook is invoked.

## fulfillmentCodeHook


The `fulfillmentCodeHook` field defines the settings for the code hook to run to fulfill the intent. It maps to the following [FulfillmentCodeHookSettings](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentCodeHookSettings.html) object:

```
"fulfillmentCodeHook": {
    "active": boolean,
    "enabled": boolean,
    "fulfillmentUpdatesSpecification": [FulfillmentUpdatesSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentUpdatesSpecification.html),
    "postFulfillmentStatusSpecification": [PostFulfillmentStatusSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostFulfillmentStatusSpecification.html)
}
```
+ Change the `active` field to `true` for Amazon Lex V2 to call the code hook at that point in the conversation.
+ Change the `enabled` field to `true` for Amazon Lex V2 to allow the code hook to run normally. If you mark it `false`, Amazon Lex V2 acts as if the code hook returned successfully.
+ Use the `fulfillmentUpdatesSpecification` field to specify the messages that appear to update the user during fulfillment of the intent and the timing associated with them.
+ Use the `postFulfillmentStatusSpecification` field to specify the messages and actions that occur after the code hook succeeds, fails, or times out.

You can invoke the Lambda code hook at the following points in a conversation by setting the `active` and `enableCodeHookInvocation`/`enabled` fields to `true`:

## During the initial response


To invoke the Lambda function in the initial response after the intent is recognized, use the `codeHook` structure in the `initialResponse` field of 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) operation. The `initialResponse` field maps to the following [InitialResponseSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_InitialResponseSetting.html) object:

```
"initialResponse": {
    "codeHook": {
        "active": boolean,
        "enableCodeHookInvocation": boolean,
        "invocationLabel": string,
        "postCodeHookSpecification": [PostDialogCodeHookInvocationSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostDialogCodeHookInvocationSpecification.html),
    },
    "initialResponse": [FulfillmentUpdatesSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentUpdatesSpecification.html),
    "nextStep": [PostFulfillmentStatusSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostFulfillmentStatusSpecification.html),
    "conditional": [ConditionalSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ConditionalSpecification.html)
}
```

## After slot elicitation or during slot re-elicitation


To invoke the Lambda function after eliciting a slot value, use the `slotCaptureSetting` field within the `valueElicitation` field of 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. The `slotCaptureSetting` field maps to the following [SlotCaptureSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_SlotCaptureSetting.html) object:

```
"slotCaptureSetting": {
    "captureConditional": [ConditionalSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ConditionalSpecification.html),
    "captureNextStep": [DialogState object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogState.html),
    "captureResponse": [ResponseSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ResponseSpecification.html),
    "codeHook": {
        "active": true,
        "enableCodeHookInvocation": true,
        "invocationLabel": string,
        "postCodeHookSpecification": [PostDialogCodeHookInvocationSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostDialogCodeHookInvocationSpecification.html),
    },
    "elicitationCodeHook": {
        "enableCodeHookInvocation": boolean,
        "invocationLabel": string
    },
    "failureConditional": [ConditionalSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ConditionalSpecification.html),
    "failureNextStep": [DialogState object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogState.html),
    "failureResponse": [ResponseSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ResponseSpecification.html)
}
```
+ To invoke the Lambda function after slot elicitation is successful, use the `codeHook` field.
+ To invoke the Lambda function after slot elicitation fails and Amazon Lex V2 attempts to retry slot elicitation, use the `elicitationCodeHook` field.

## After intent confirmation or denial


To invoke the Lambda function when confirming an intent, use the `intentConfirmationSetting` field of 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) operation. The `intentConfirmation` field maps to the following [IntentConfirmationSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_IntentConfirmationSetting.html) object:

```
"intentConfirmationSetting": {
    "active": boolean,
    "codeHook": {
        "active": boolean,
        "enableCodeHookInvocation": boolean,
        "invocationLabel": string,
        "postCodeHookSpecification": [PostDialogCodeHookInvocationSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostDialogCodeHookInvocationSpecification.html),
    },
    "confirmationConditional": [ConditionalSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ConditionalSpecification.html),
    "confirmationNextStep": [DialogState object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogState.html),
    "confirmationResponse": [ResponseSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialResponseSpecificationogState.html),
    "declinationConditional": [ConditionalSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ConditionalSpecification.html),
    "declinationNextStep": [FulfillmentUpdatesSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentUpdatesSpecification.html),
    "declinationResponse": [PostFulfillmentStatusSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostFulfillmentStatusSpecification.html),
    "elicitationCodeHook": {
        "enableCodeHookInvocation": boolean,
        "invocationLabel": string,
    },
    "failureConditional": [ConditionalSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ConditionalSpecification.html),
    "failureNextStep": [DialogState object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogState.html),
    "failureResponse": [ResponseSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ResponseSpecification.html),
    "promptSpecification": [PromptSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PromptSpecification.html)
}
```
+ To invoke the Lambda function after the user confirms the intent and its slots, use the `codeHook` field.
+ To invoke the Lambda function after the user denies the intent confirmation and Amazon Lex V2 attempts to retry slot elicitation, use the `elicitationCodeHook` field.

## During intent fulfillment


To invoke the Lambda function to fulfill an intent, use the `fulfillmentCodeHook` field in 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) operation. The `fulfillmentCodeHook` field maps to the following [FulfillmentCodeHookSettings](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentCodeHookSettings.html) object:

```
{
    "active": boolean,
    "enabled": boolean,
    "fulfillmentUpdatesSpecification": [FulfillmentUpdatesSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentUpdatesSpecification.html),
    "postFulfillmentStatusSpecification": [PostFulfillmentStatusSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostFulfillmentStatusSpecification.html)
}
```

3. Once you set the conversation stages at which to invoke the Lambda function, use the `BuildBotLocale` operation to rebuild the bot in order to test the function.

# Debugging a Lambda function using CloudWatch Logs logs
Debugging a Lambda function

[Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) is a tool for tracking API calls and metrics that you can use to help debug your Lambda functions. When you test your bot in the console or with API calls, CloudWatch logs each step of the conversation. If you use a print function in your Lambda code, CloudWatch displays it as well.

**To view CloudWatch logs for your Lambda function**

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

1. Under the **Logs** menu in the left side bar, select **Log groups**.

1. Select your Lambda function log group, which should be of the format `/aws/lambda/function-name`.

1. The list of **Log streams** contains a log for each session with a bot. Choose a log stream to view it.

1. In the list of **Log events**, select the right arrow next to the **Timestamp** to expand the details for that event. Anything you print from your Lambda code will appear as a log event. Use this information to debug your code.

1. After you debug your code, remember to **Deploy** the Lambda function and, if you are using the console, to reload the **Test** window before re-testing the bot's behavior.