

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 將 AWS Lambda函數整合到您的 Amazon Lex V2 機器人
<a name="lambda"></a>

使用 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)函數，您可以透過您定義的自訂函數來擴展和更好地控制 Amazon Lex V2 機器人的行為。Amazon Lex V2 每個語言的每個機器人別名使用一個 Lambda 函數，而不是每個意圖使用一個 Lambda 函數。開始之前，請判斷您要從[輸入事件](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-input-format)中提取資訊的欄位，以及您要從 Lambda 函數操作和傳回的[回應](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-response-format)中的欄位

若要將 Lambda 函數與您的 Amazon Lex V2 機器人整合，請執行下列步驟：

1. AWS Lambda使用您選擇的程式設計語言在 中[建立函數](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach)，並撰寫指令碼。

1. 確定函數傳回符合[回應格式](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-response-format)的結構。

1. 部署 Lambda 函數。

1. 將 Lambda 函數與 Amazon Lex V2 機器人別名與[主控台](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-console)或 [API 操作](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-api)建立關聯。

1. 選取您要使用[主控台](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-console)或 [API 操作](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-attach-api)調用 Lambda 函數的對話階段。

1. 建置您的 Amazon Lex V2 機器人，並測試 Lambda 函數是否如預期般運作。[在 Amazon CloudWatch 的協助下偵錯](https://docs.aws.amazon.com/lexv2/latest/dg/lambda-debug)函數。 Amazon CloudWatch

**Topics**
+ [AWS LambdaLex V2 的輸入事件格式](lambda-input-format.md)
+ [AWS LambdaLex V2 的回應格式](lambda-response-format.md)
+ [Amazon Lex V2 AWS Lambda函數中的常見結構](lambda-common-structures.md)
+ [為您的 Amazon Lex V2 機器人建立 AWS Lambda函數](lambda-attach.md)
+ [使用 CloudWatch Logs 日誌對 Lambda 函數進行偵錯](lambda-debug.md)

# AWS LambdaLex V2 的輸入事件格式
<a name="lambda-input-format"></a>

將 Lambda 函數整合到 Amazon Lex V2 機器人的第一步是了解 Amazon Lex V2 事件中的欄位，並確定您在編寫指令碼時要使用的這些欄位中的資訊。下列 JSON 物件顯示傳遞至 Lambda 函數的 Amazon Lex V2 事件一般格式：

**注意**  
輸入格式可能會變更，而不會對 進行對應的變更`messageVersion`。如果出現新的欄位，您的程式碼不應擲回錯誤。

```
{
    "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 意圖 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 意圖 for details about the structure
        },
        "prompt": {
            "attempt": string 
        }
    },
    "requestAttributes": {
        string: string,
        ...
    },
    "sessionState": {
        // see 工作階段狀態 for details about the structure
    },
    "transcriptions": [
        {
            "transcription": string,
            "transcriptionConfidence": number,
            "resolvedContext": {
                "intent": string
            },
            "resolvedSlots": {
                slot name: {
                    // see 槽 for details about the structure
                },
                ...
            }
        },
        ...
    ]
}
```

輸入事件中的每個欄位如下所述：

## messageVersion
<a name="lambda-input-messageversion"></a>

訊息的版本，可識別進入 Lambda 函數的事件資料格式，以及來自 Lambda 函數的預期回應格式。

**注意**  
您在定義意圖時設定此值。在目前的實作中，Amazon Lex V2 僅支援訊息版本 1.0。因此，主控台假設 1.0 的預設值，而且不會顯示訊息的版本。

## invocationSource
<a name="lambda-input-invocationsource"></a>

稱為 Lambda 函數的程式碼掛鉤。可能的值如下：

`DialogCodeHook` – Amazon Lex V2 從使用者輸入後呼叫 Lambda 函數。

`FulfillmentCodeHook` – Amazon Lex V2 在填入所有必要插槽且意圖已準備好履行之後，便呼叫 Lambda 函數。

## inputMode
<a name="lambda-input-inputmode"></a>

使用者表達用語的模式。可能的值如下：

`DTMF` – 使用者使用按鍵式鍵盤 （雙音多頻率） 輸入表達用語。

`Speech` – 使用者說出表達用語。

`Text` – 使用者輸入表達用語。

## responseContentType
<a name="lambda-input-responsecontenttype"></a>

機器人對使用者回應的模式。 `text/plain; charset=utf-8`表示已寫入最後一個表達式，而以 開頭的值`audio`表示已說出最後一個表達式。

## sessionId
<a name="lambda-input-sessionid"></a>

用於對話的英數工作階段識別符。

## inputTranscript
<a name="lambda-input-inputtranscript"></a>

來自使用者的輸入轉錄。
+ 對於文字輸入，這是使用者輸入的文字。對於 DTMF 輸入，這是使用者輸入的金鑰。
+ 對於語音輸入，這是 Amazon Lex V2 轉換使用者表達用語以叫用意圖或填入槽的文字。

## invocationLabel
<a name="lambda-input-invocationlabel"></a>

指出叫用 Lambda 函數之回應的值。您可以設定初始回應、槽和確認回應的調用標籤。

## 機器人
<a name="lambda-input-bot"></a>

處理請求之機器人的相關資訊，包含下列欄位：
+ **id** – 在您建立機器人時指派給機器人的識別符。您可以在機器人**設定**頁面的 Amazon Lex V2 主控台中查看機器人 ID。
+ **name** – 您在建立機器人時提供給機器人的名稱。
+ **localeId** – 您用於機器人之地區設定的識別符。如需地區設定清單，請參閱 [Amazon Lex V2 支援的語言和地區設定](how-languages.md)。
+ **版本** – 處理請求的機器人版本。
+ **aliasId** – 建立機器人別名時指派給機器人別名的識別符。您可以在別名頁面的 Amazon Lex V2 ****主控台中查看機器人別名 ID。如果您在清單中看不到別名 ID，請選擇右上角的齒輪圖示，然後開啟**別名 ID**。
+ **aliasName** – 您給機器人別名的名稱。

## 解釋
<a name="lambda-input-interpretations"></a>

Amazon Lex V2 認為可能符合使用者表達用語之意圖的相關資訊清單。每個項目都是一個結構，提供表達用語與意圖相符的相關資訊，格式如下：

```
{
    "intent": {
        // see 意圖 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
        }
    }
}
```

結構中的欄位如下所示：
+ **意圖** – 包含意圖相關資訊的結構。[意圖](lambda-common-structures.md#lambda-intent) 如需結構的詳細資訊，請參閱 。
+ **nluConfidence** – 表示 Amazon Lex V2 對意圖符合使用者意圖的可信度的分數。
+ **sentimentResponse** – 回應情緒的分析，其中包含下列欄位：
  + **情緒** – 指出表達用語的情緒是 `POSITIVE`、`NEUTRAL`、 `NEGATIVE`或 `MIXED`。
  + **sentimentScore** – 將每個情緒映射至數字的結構，指出 Amazon Lex V2 對表達該情緒的信心有多高。
+ **interpretationSource** – 指出插槽是由 Amazon Lex V2 或 Amazon Bedrock 解析。

## proposedNextState
<a name="lambda-input-proposednextstate"></a>

如果 Lambda 函數將 `dialogAction`的 設定為 `sessionState` `Delegate`，則會顯示此欄位，並顯示 Amazon Lex V2 在對話中下一個步驟的提案。否則，下一個狀態取決於您在 Lambda 函數的回應中傳回的設定。只有在下列兩個陳述式都為 true 時，才會出現此結構：

1. `invocationSource` 值為 `DialogCodeHook`

1. `type` 的預測`dialogAction`為 `ElicitSlot`。

您可以使用此資訊在對話`runtimeHints`的正確位置新增 。[改善對話中具有執行時間提示的槽值辨識](using-hints.md) 如需詳細資訊，請參閱 。 `proposedNextState` 是包含下列欄位的結構：

的結構`proposedNextState`如下：

```
"proposedNextState": {
    "dialogAction": {
        "slotToElicit": string,
        "type": "Close | ConfirmIntent | Delegate | ElicitIntent | ElicitSlot"
    },
    "intent": {
        // see 意圖 for details about the structure
    },
    "prompt": {
        "attempt": string 
    }
}
```
+ **dialogAction** – 包含 Amazon Lex V2 提議的下一個步驟的相關資訊。結構中的欄位如下所示：
  + **slotToElicit** – Amazon Lex V2 建議接下來引出的插槽。只有在 `type`為 時，才會顯示此欄位`ElicitSlot`。
  + **type** – Amazon Lex V2 建議的對話中的下一個步驟。可能的值如下：

    `Delegate` – Amazon Lex V2 會決定下一個動作。

    `ElicitIntent` – 下一個動作是從使用者引出意圖。

    `ElicitSlot` – 下一個動作是從使用者引出槽值。

    `Close` – 結束意圖履行程序，並指出不會有來自使用者的回應。

    `ConfirmIntent` – 下一個動作是詢問使用者槽是否正確，以及意圖是否已準備好履行。
+ **意圖** – 機器人判斷使用者正在嘗試履行的意圖。[意圖](lambda-common-structures.md#lambda-intent) 如需結構的詳細資訊，請參閱 。
+ prompt**** – 包含欄位 的結構`attempt`，會映射至指定 Amazon Lex V2 提示使用者輸入下一個槽的次數的值。可能的值`Initial`適用於第一次嘗試`Retry1`，以及後續嘗試`Retry5`的 `Retry2``Retry3`、`Retry4`、、 和 。

## requestAttributes
<a name="lambda-input-requestattributes"></a>

包含用戶端在請求中傳送之請求特定屬性的結構。使用請求屬性來傳遞不需要在整個工作階段內保留的資訊。若無請求屬性，則數值將為 null。如需詳細資訊，請參閱[設定 Lex V2 機器人的請求屬性](context-mgmt-request-attribs.md)。

## sessionState
<a name="lambda-input-sessionstate"></a>

使用者與 Amazon Lex V2 機器人之間對話的目前狀態。[工作階段狀態](lambda-common-structures.md#lambda-session-state) 如需結構的詳細資訊，請參閱 。

## 轉錄
<a name="lambda-input-transcriptions"></a>

Amazon Lex V2 認為可能符合使用者表達用語的轉錄清單。如需詳細資訊，請參閱[使用語音轉錄可信度分數來改善與 Lex V2 機器人的對話](using-transcript-confidence-scores.md)。每個項目都是具有下列格式的物件，其中包含一個可能轉錄的相關資訊：

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

這些欄位如下所述：
+ **轉錄** – Amazon Lex V2 認為可能符合使用者音訊表達用語的轉錄。
+ **transcriptionConfidence** – 表示 Amazon Lex V2 對意圖符合使用者意圖的可信度的分數。
+ **resolvedContext** – 包含 欄位 的結構`intent`，對應到表達用語相關的意圖。
+ **resolvedSlots** – 一種結構，其索引鍵是表達式解析的每個槽的名稱。每個槽名稱都會映射到包含該槽相關資訊的結構。[槽](lambda-common-structures.md#lambda-slot) 如需結構的詳細資訊，請參閱 。

# AWS LambdaLex V2 的回應格式
<a name="lambda-response-format"></a>

將 Lambda 函數整合至 Amazon Lex V2 機器人的第二個步驟是了解 Lambda 函數回應中的欄位，並判斷您要操作的參數。下列 JSON 物件顯示傳回 Amazon Lex V2 的 Lambda 回應一般格式：

```
{
    "sessionState": {
        // see 工作階段狀態 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,
        ...
    }
}
```

回應中的每個欄位如下所述：

## sessionState
<a name="lambda-response-sessionstate"></a>

您要傳回的使用者和 Amazon Lex V2 機器人之間的對話狀態。[工作階段狀態](lambda-common-structures.md#lambda-session-state) 如需結構的詳細資訊，請參閱 。此欄位一律為必要欄位。

## messages
<a name="lambda-response-messages"></a>

Amazon Lex V2 傳回給客戶的訊息清單，以供下次對話使用。如果您`contentType`提供的 是 `PlainText`、 `CustomPayload`或 `SSML`，請在 `content` 欄位中寫入您要傳回給客戶的訊息。如果您`contentType`提供的 是 `ImageResponseCard`，請在 `imageResponseCard` 欄位中提供卡片的詳細資訊。如果您未提供訊息，Amazon Lex V2 會使用建立機器人時定義的適當訊息。

如果 `dialogAction.type`是 `ElicitIntent`或 ，則 `messages` 欄位為必要`ConfirmIntent`。

清單中的每個項目都是以下格式的結構，其中包含要傳回給使用者的訊息相關資訊。請見此處範例：

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

每個欄位的說明如下：
+ **contentType** – 要使用的訊息類型。

  `CustomPayload` – 您可以自訂的回應字串，以包含應用程式的資料或中繼資料。

  `ImageResponseCard` – 具有客戶可以選擇之按鈕的影像。如需詳細資訊，請參閱 [ImageResponseCard](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_ImageResponseCard.html)。

  `PlainText` – 純文字字串。

  `SSML` – 包含語音合成標記語言的字串，用於自訂音訊回應。
+ **內容** – 要傳送給使用者的訊息。如果訊息類型為 `PlainText`、 或 `CustomPayload`，請使用此欄位`SSML`。
+ **imageResponseCard** – 包含要向使用者顯示的回應卡定義。如果訊息類型為 ，請使用此欄位`ImageResponseCard`。映射至包含下列欄位的結構：
  + **title** – 回應卡的標題。
  + **字幕** – 提示使用者選擇按鈕。
  + **imageUrl** – 卡片影像的連結。
  + **按鈕** – 包含按鈕相關資訊的結構清單。每個結構都包含一個`text`欄位，其中包含要顯示的文字，以及如果客戶選取該按鈕，則包含要傳送至 Amazon Lex V2 之值`value`的欄位。您最多可以包含三個按鈕。

## requestAttributes
<a name="lambda-response-requestattributes"></a>

包含回應客戶之請求特定屬性的結構。如需詳細資訊，請參閱[設定 Lex V2 機器人的請求屬性](context-mgmt-request-attribs.md)。此欄位為選用欄位。

## 回應中的必要欄位
<a name="lambda-response-required"></a>

至少，Lambda 回應必須包含`sessionState`物件。在其中，提供`dialogAction`物件並指定 `type` 欄位。根據您`dialogAction`提供的 `type` ，Lambda 回應可能還有其他必要欄位。這些要求描述如下，以及最少的工作範例：

### 委派代表
<a name="lambda-response-delegate"></a>

**委派**可讓 Amazon Lex V2 決定下一個步驟。不需要其他欄位。

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

### ElicitIntent
<a name="lambda-response-elicitintent"></a>

**ElicitIntent** 會提示客戶表達意圖。您必須在 `messages` 欄位中包含至少一個訊息，以提示引出意圖。

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

### ElicitSlot
<a name="lambda-response-elicitslot"></a>

**ElicitSlot** 會提示客戶提供槽值。您必須在 `dialogAction` 物件的 `slotToElicit` 欄位中包含插槽的名稱。您還必須在 `sessionState` 物件`intent`中包含 `name`的 。

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

### ConfirmIntent
<a name="lambda-response-confirmintent"></a>

**ConfirmIntent** 會確認客戶的槽值，以及是否已準備好履行意圖。您必須在 `sessionState` 物件`intent`中包含 `name`的 ，以及`slots`要確認的 。您也必須在 `messages` 欄位中包含至少一個訊息，以要求使用者確認槽值。您的訊息應提示「是」或「否」回應。如果使用者回應「是」，Amazon Lex V2 會將意圖`confirmationState`的 設定為 `Confirmed`。如果使用者回應「否」，Amazon Lex V2 會將意圖`confirmationState`的 設定為 `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 (關閉)
<a name="lambda-response-close"></a>

**關閉**會結束意圖的履行程序，並指出預期使用者不會進一步回應。您必須在 `sessionState` 物件`intent`中包含 `state`的 `name`和 。相容意圖狀態為 `Failed`、 `Fulfilled`和 `InProgress`。

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

# Amazon Lex V2 AWS Lambda函數中的常見結構
<a name="lambda-common-structures"></a>

在 Lambda 回應中，有許多結構會重複發生。本節提供這些常見結構的詳細資訊。

## 意圖
<a name="lambda-intent"></a>

```
"intent": {
    "confirmationState": "Confirmed | Denied | None",
    "name": string,
    "slots": {
        // see 槽 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       }
}
```

`intent` 欄位會映射至具有下列欄位的物件：

### confirmationState
<a name="lambda-intent-confirmationstate"></a>

指出使用者是否已確認意圖的槽，且意圖已準備好履行。可能的值如下：

`Confirmed` – 使用者確認槽值正確。

`Denied` – 使用者表示槽值不正確。

`None` – 使用者尚未到達確認階段。

### name
<a name="lambda-intent-name"></a>

意圖的名稱。

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

完成意圖所需的槽資訊。[槽](#lambda-slot) 如需結構的詳細資訊，請參閱 。

### state
<a name="lambda-intent-state"></a>

指出意圖的履行狀態。可能的值如下：

`Failed` – 機器人無法滿足意圖。

`Fulfilled` – 機器人已完成意圖的履行。

`FulfillmentInProgress` – 機器人正在履行意圖。

`InProgress` – 機器人正在引發滿足意圖所需的槽值。

`ReadyForFulfillment` – 機器人已引出意圖的所有槽值，並準備好滿足意圖。

`Waiting` – 機器人正在等待使用者的回應 （僅限於串流對話）。

### kendraResponse
<a name="lambda-intent-kendraresponse"></a>

包含 Kendra 搜尋查詢結果的相關資訊。只有在意圖為 時，才會顯示此欄位`KendraSearchIntent`。如需詳細資訊[，請參閱 Kendra 的查詢 API 呼叫中的回應語法](https://docs.aws.amazon.com/kendra/latest/dg/API_Query.html#API_Query_ResponseSyntax)。

## 槽
<a name="lambda-slot"></a>

`slots` 欄位存在於 `intent` 結構中，並映射到其索引鍵為該意圖槽名稱的結構。如果插槽不是多值插槽 （如需詳細資訊[在槽中使用多個值](multi-valued-slots.md)，請參閱 )，則會對應至具有下列格式的結構。請注意， `shape`是 `Scalar`。

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

如果插槽是多值插槽，則其對應的物件包含另一個名為 的欄位`values`，其會對應至結構清單，每個欄位都包含構成多值插槽的插槽相關資訊。清單中每個物件的格式符合一般槽所對應的物件格式。請注意， `shape`是 `List`，但 下的元件插槽`shape`的 `values`是 `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,
                    ...
                ]
            }
        },
        ...
    ]
}
```

槽物件中的欄位如下所述：

### shape
<a name="lambda-slots-shape"></a>

槽的形狀。`List` 如果槽中有多個值 （如需詳細資訊[在槽中使用多個值](multi-valued-slots.md)，請參閱 )，則此值為 ，`Scalar`否則為 。

### value
<a name="lambda-slots-value"></a>

包含使用者為插槽提供的值和 Amazon Lex V2 解釋相關資訊的物件，格式如下：

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

這些欄位如下所述：
+ **originalValue** – 使用者對 Amazon Lex V2 確定與槽值相關的槽引出的回應部分。
+ **interpretedValue** – Amazon Lex V2 根據使用者輸入決定的槽值。
+ **resolvedValues** – Amazon Lex V2 判斷為使用者輸入可能解析度的值清單。

### values
<a name="lambda-slots-values"></a>

物件清單，其中包含構成多值槽的槽相關資訊。每個物件的格式都符合正常槽的格式，以及上述的 `shape`和 `value` 欄位。`values`只有在該槽包含多個值時才會顯示 （如需詳細資訊[在槽中使用多個值](multi-valued-slots.md)，請參閱 )。下列 JSON 物件顯示兩個元件插槽：

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

## 工作階段狀態
<a name="lambda-session-state"></a>

`sessionState` 欄位會映射至 物件，其中包含與使用者對話狀態的相關資訊。物件中出現的實際欄位取決於對話方塊動作的類型。如需 Lambda 回應中的必要欄位，[回應中的必要欄位](lambda-response-format.md#lambda-response-required)請參閱 。`sessionState` 物件的格式如下：

```
"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 意圖 for details about the structure
    },
    "originatingRequestId": string
}
```

這些欄位如下所述：

### activeContexts
<a name="lambda-active-contexts"></a>

物件清單，其中包含使用者在工作階段中使用的內容相關資訊。使用內容來促進和控制意圖辨識。如需內容的詳細資訊，請參閱 [設定 Lex V2 機器人的意圖內容](context-mgmt-active-context.md)。每個物件的格式如下：

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

這些欄位如下所述：
+ **name** – 內容的名稱。
+ **contextAttributes** – 物件，其中包含內容的屬性名稱及其對應的值。
+ **timeToLive** – 指定內容保持作用中狀態的物件。此物件可以包含下列其中一個或兩個欄位：
  + **timeToLiveInSeconds** – 內容保持作用中的秒數。
  + **turnsToLive** – 內容保持作用中的轉彎次數。

### sessionAttributes
<a name="lambda-session-attributes"></a>

代表工作階段特定內容資訊的鍵/值對映射。如需詳細資訊，請參閱[設定 Lex V2 機器人的工作階段屬性](context-mgmt-session-attribs.md)。物件的格式如下所示：

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

### runtimeHints
<a name="lambda-runtime-hints"></a>

提供提示給客戶可能用於槽的片語，以改善音訊辨識。您在提示中提供的值會提升這些值的音訊辨識能力，而不是類似聲音的單字。`runtimeHints` 物件的格式如下：

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

`slotHints` 欄位映射到物件，其欄位是機器人中意圖的名稱。每個意圖名稱都會映射到一個物件，其欄位是該意圖的槽名稱。每個槽名稱都會映射到具有單一欄位 的結構`runtimeHintValues`，這是物件清單。每個物件都包含一個映射到提示`phrase`的欄位。

### dialogAction
<a name="lambda-dialog-action"></a>

決定 Amazon Lex V2 要採取的下一個動作。物件的格式如下所示：

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

這些欄位如下所述：
+  **slotElicitationStyle** – 如果 `type``dialogAction`為 ，則決定 Amazon Lex V2 如何解譯使用者的音訊輸入`ElicitSlot`。如需詳細資訊，請參閱[在對話期間使用拼寫樣式擷取槽值](spelling-styles.md)。可能的值如下：

  `Default` – Amazon Lex V2 會以預設方式解譯音訊輸入，以滿足插槽。

  `SpellByLetter` – Amazon Lex V2 會接聽使用者拼寫的槽值。

  `SpellByWord` – Amazon Lex V2 會使用與每個字母相關聯的單字 （例如 Apple 中的「a」) 接聽使用者拼法的槽值。
+  **slotToElicit** – 如果 `dialogAction`為 ，則定義要從使用者引出`type`的插槽`ElicitSlot`。
+ **type** – 定義機器人應執行的動作。可能的值如下：

  `Delegate` – 讓 Amazon Lex V2 決定下一個步驟。

  `ElicitIntent` – 提示客戶表達意圖。

  `ConfirmIntent` – 確認客戶的槽值，以及意圖是否已準備好履行。

  `ElicitSlot` – 提示客戶提供意圖的槽值。

  `Close` – 結束意圖履行程序。

### intent
<a name="lambda-sessionstate-intent"></a>

如需 `intent` 欄位的結構[意圖](#lambda-intent)，請參閱 。

### originatingRequestId
<a name="lambda-originating-request-id"></a>

請求的唯一識別符。此欄位對於 Lambda 回應是選用的。

# 為您的 Amazon Lex V2 機器人建立 AWS Lambda函數
<a name="lambda-attach"></a>

若要為 Amazon Lex V2 機器人建立 Lambda 函數，AWS Lambda請從 AWS 管理主控台存取 並建立新的函數。如需詳細資訊，請參閱 [AWS Lambda開發人員指南](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)AWS Lambda。

1. 登入 AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) 開啟AWS Lambda主控台。

1. 選擇左側邊欄中**的函數**。

1. 選取 **Create function** (建立函式)。

1. 您可以選取**從頭開始撰寫**以最小程式碼、**使用藍圖**從清單中選取常見使用案例的範例程式碼，或**選取容器映像**來選取要為函數部署的容器映像。如果您**從頭選取作者**，請繼續執行下列步驟：

   1. 為您的函數提供有意義的**函數名稱**，以描述其功能。

   1. 從**執行時間**下的下拉式選單中選擇語言，以寫入函數。

   1. 為您的函數選取指令集**架構**。

   1. 根據預設，Lambda 會建立具有基本許可的角色。若要使用現有角色或使用 AWS 政策範本建立角色，請展開**變更預設執行角色**功能表，然後選取 選項。

   1. 展開**進階設定**選單以設定更多選項。

1. 選取 **Create function** (建立函式)。

下圖顯示從頭開始建立新函數時看到的內容：

![\[新的 Lambda 函數。\]](http://docs.aws.amazon.com/zh_tw/lexv2/latest/dg/images/lambda/lambda-new-function.png)


Lambda 處理常式函數會根據您使用的語言而有所不同。它至少需要 `event` JSON 物件做為引數。您可以在 Amazon Lex V2 `event` 提供的 中查看欄位[AWS LambdaLex V2 的輸入事件格式](lambda-input-format.md)。修改處理常式函數，以最終傳回符合 中所述格式的 `response` JSON 物件[AWS LambdaLex V2 的回應格式](lambda-response-format.md)。
+ 完成撰寫函數後，請選取**部署**以允許使用函數。

請記住，您可以將每個機器人別名與最多一個 Lambda 函數建立關聯。不過，您可以在 Lambda 程式碼中為機器人定義任意數量的函數，並在 Lambda 處理常式函數中呼叫這些函數。例如，雖然相同機器人別名中的所有意圖都必須呼叫相同的 Lambda 函數，但您可以建立路由器函數，為每個意圖啟用個別的函數。以下是您可以針對應用程式使用或修改的範例路由器函數：

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

**在 Amazon Lex V2 機器人對話中使用 AWS Lambda函數的時機**

您可以在與使用者對話的下列時間點使用 Lambda 函數：
+ 在辨識意圖後的初始回應中。例如，在使用者說他們想要訂購比薩之後。
+ 從使用者引出槽值之後。例如，在使用者告知機器人要訂購的比薩大小之後。
+ 在每次嘗試引出槽之間。例如，如果客戶不使用可辨識的比薩大小。
+ 確認意圖時。例如，確認比薩訂單時。
+ 實現意圖。例如，訂購比薩。
+ 在滿足意圖之後，以及機器人關閉對話之前。例如，切換到訂購飲料的意圖。

**Topics**
+ [使用主控台將 AWS Lambda函數連接至 Amazon Lex V2 機器人](lambda-attach-console.md)
+ [使用 API 操作將 AWS Lambda函數連接至 Amazon Lex V2 機器人](lambda-attach-api.md)

# 使用主控台將 AWS Lambda函數連接至 Amazon Lex V2 機器人
<a name="lambda-attach-console"></a>

您必須先將 Lambda 函數連接至 Amazon Lex V2 機器人別名，才能叫用它。每個機器人別名只能連接一個 Lambda 函數。執行這些步驟，以使用 AWS 主控台連接 Lambda 函數。

1. 登入 AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/) 開啟 Amazon Lex 主控台。

1. 從左側面板中選擇**機器人**，然後從機器人清單中選擇您要連接 Lambda 函數的機器人名稱。

1. 在左側面板中，選取**部署**功能表下的**別名**。

1. 從別名清單中，選擇您要連接 Lambda 函數的別名名稱。

1. 在**語言**面板中，選取您要 Lambda 函數使用的語言。如果面板中沒有語言，請選取**管理別名中的**語言來新增語言。

1. 在**來源**下拉式功能表中，選擇您要連接的 Lambda 函數名稱。

1. 在 **Lambda 函數版本或別名**下拉式功能表中，選擇您要使用的 Lambda 函數版本或別名。然後選取 **Save (儲存)**。相同的 Lambda 函數用於機器人支援的語言中的所有意圖。

**設定 Amazon Lex V2 意圖，以使用主控台叫用 Lambda 函數**

1. 選取機器人後，在左側選單中，選取您要叫用 Lambda 函數之機器人語言下的**意圖**。

1. 選擇您要叫用 Lambda 函數的意圖，以開啟意圖編輯器。

1. 有兩種設定 Lambda 程式碼掛勾的選項：

   1. 若要在對話的每個步驟之後叫用 Lambda 函數，請捲動至意圖編輯器底部的**程式碼掛**勾區段，然後選取**使用 Lambda 函數進行初始化和驗證**核取方塊，如下圖所示：  
![\[Amazon Lex V2 意圖編輯器的程式碼掛勾區段。\]](http://docs.aws.amazon.com/zh_tw/lexv2/latest/dg/images/lambda/lambda-code-hooks-all.png)

   1. 或者，在叫用 Lambda 函數的對話階段中使用**對話方塊程式碼掛**勾區段。**對話方塊程式碼掛接**區段顯示如下：  
![\[Amazon Lex V2 意圖編輯器的程式碼掛勾區段。\]](http://docs.aws.amazon.com/zh_tw/lexv2/latest/dg/images/lambda/lambda-code-hook-step.png)

      有兩種方式可以控制 Amazon Lex V2 如何呼叫程式碼掛鉤來回應：
      + 切換**作用中**按鈕以將其標記為*作用中*或非*作用中*。當程式碼掛鉤處於*作用中*狀態時，Amazon Lex V2 會呼叫程式碼掛鉤。當程式碼掛鉤處於*非作用中*狀態時，Amazon Lex V2 不會執行程式碼掛鉤。
      + 展開 **Lambda 對話方塊程式碼掛勾**區段，然後選取**叫用 Lambda 函數**核取方塊，將其標記為*啟用或停用***。您只能在程式碼掛鉤標示為作用中時啟用或停用該程式碼掛鉤。標示為*啟用*時，程式碼掛鉤會正常執行。*停用*時，不會呼叫程式碼掛鉤，Amazon Lex V2 就像成功傳回程式碼掛鉤一樣。若要在對話方塊程式碼掛鉤成功、失敗或逾時後設定回應，請選取**進階選項**

      您可以在下列對話階段叫用 Lambda 程式碼掛勾：
      + 若要呼叫函數做為**初始回應**，請捲動至**初始回應**區段，展開**回應旁的箭頭以確認使用者的請求**，然後選取**進階選項**。尋找快顯功能表底部的**對話方塊程式碼掛**勾區段。
      + 若要在**槽引出**後叫用函數，請捲動至**槽**區段，展開相關**槽提示**旁的箭頭，然後選取**進階選項**。尋找快顯功能表底部附近的**對話方塊程式碼掛**接區段，就在**預設值**上方。

        您也可以在每次引出後叫用 函數。若要這樣做，請在**槽提示**區段中展開**機器人引出資訊**，選取**更多提示選項**，然後選取**每次引出後叫用 Lambda 程式碼掛**勾旁的核取方塊。
      + 若要叫用 函數進行**意圖確認**，請捲動至**確認**區段，展開**提示旁的箭頭以確認意圖**，然後選取**進階選項**。尋找快顯功能表底部的**對話方塊程式碼掛**勾區段。
      + 若要叫用 函數以進行**意圖履行**，請捲動至**履行**區段。切換**作用中**按鈕，將程式碼掛鉤設定為*作用中*。展開**成功履行**旁的箭頭，然後選取**進階選項**。選取 **Fulfillment** **Lambda 程式碼掛勾區段下的使用 Lambda 函數履行**旁的核取方塊，將程式碼掛勾設定為*啟用*。

1. 設定叫用 Lambda 函數的對話階段後，請再次**建置**機器人以測試函數。

# 使用 API 操作將 AWS Lambda函數連接至 Amazon Lex V2 機器人
<a name="lambda-attach-api"></a>

您必須先將 Lambda 函數連接至 Amazon Lex V2 機器人別名，才能叫用它。您只能將一個 Lambda 函數與每個機器人別名建立關聯。執行這些步驟，以使用 API 操作連接 Lambda 函數。

如果您要建立新的機器人別名，請使用 [CreateBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateBotAlias.html) 操作來連接 Lambda 函數。若要將 Lambda 函數連接至現有的機器人別名，請使用 [UpdateBotAlias](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateBotAlias.html) 操作。修改 `botAliasLocaleSettings` 欄位以包含正確的設定：

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

1. `botAliasLocaleSettings` 欄位會映射到物件，其金鑰是您要連接 Lambda 函數的地區設定。[支援的語言和地區設定](how-languages.md#supported-languages) 如需支援的地區設定清單和有效金鑰的代碼，請參閱 。

1. 若要尋找 Lambda 函數`lambdaARN`的 ，請在 https：//[https://console.aws.amazon.com/lambda/home](https://console.aws.amazon.com/lambda/home) 開啟AWS Lambda主控台，選取**左側邊欄中的函數**，然後選取要與機器人別名建立關聯的函數。在**函數概觀**的右側，找到**函數 ARN** `lambdaARN`下的 。它應該包含區域、帳戶 ID 和函數的名稱。

1. 若要允許 Amazon Lex V2 叫用別名的 Lambda 函數，請將 `enabled` 欄位設定為 `true`。

**設定 Amazon Lex V2 意圖以使用 API 操作叫用 Lambda 函數**

若要在意圖期間設定 Lambda 函數叫用，如果您要建立新的意圖，請使用 [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) 操作；如果您在現有意圖中叫用函數，請使用 [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) 操作。在意圖操作中控制 Lambda 函數調用的欄位為 `dialogCodeHook`、`intentConfirmationSetting`、 `initialResponseSetting`和 `fulfillmentCodeHook`。

如果您在引發槽時叫用 函數，如果您要建立新的槽，請使用 [CreateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateSlot.html) 操作，或 [UpdateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateSlot.html) 操作來叫用現有槽中的函數。在槽操作中控制 Lambda 函數調用的欄位是 `valueElicitationSetting` 物件`slotCaptureSetting`的 。

1. 若要將 Lambda 對話方塊程式碼掛鉤設定為在每次對話後執行，請將 `enabled` 欄位中下列 [DialogCodeHookSettings](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogCodeHookSettings.html) 物件的 `dialogCodeHook` 欄位設定為 `true`：

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

1. 或者，您可以將 Lambda 對話方塊程式碼掛鉤設定為僅在對話中的特定時間點執行，方法是修改結構中的 `codeHook`和/或 `elicitationCodeHook` 欄位，對應至您要叫用函數的對話階段。若要使用 Lambda 對話方塊程式碼勾點來執行意圖履行，請使用 [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) 或 [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) 操作中的 `fulfillmentCodeHook` 欄位。這三種類型的程式碼掛鉤的結構和用途如下所示：

## codeHook
<a name="lambda-code-hook"></a>

`codeHook` 欄位定義程式碼掛鉤在對話中指定階段執行的設定。這是具有下列結構的 [DialogCodeHookInvocationSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_DialogCodeHookInvocationSetting.html) 物件：

```
"codeHook": {
    "active": boolean,
    "enableCodeHookInvocation": boolean,
    "invocationLabel": string,
    "postCodeHookSpecification": [PostDialogCodeHookInvocationSpecification object](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_PostDialogCodeHookInvocationSpecification.html),
}
```
+ 將 `active` Amazon Lex V2 `true` 的欄位變更為 ，以在對話中的該時間點呼叫程式碼掛勾。
+ 將 `enableCodeHookInvocation` Amazon Lex V2 `true` 的欄位變更為 ，以允許程式碼掛鉤正常執行。如果您標記 `false`，Amazon Lex V2 就像程式碼掛鉤成功傳回一樣。
+ `invocationLabel` 指出從中叫用程式碼掛鉤的對話方塊步驟。
+ 使用 `postCodeHookSpecification` 欄位來指定程式碼掛鉤成功、失敗或逾時之後發生的動作和訊息。

## elicitationCodeHook
<a name="lambda-elicitation-code-hook"></a>

`elicitationCodeHook` 欄位定義程式碼掛鉤在需要重新引出插槽時要執行的設定。如果槽引出失敗或意圖確認遭拒，可能會發生這種情況。`elicitationCodeHook` 欄位是具有下列結構的 [ElicitationCodeHookInvocationSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_ElicitationCodeHookInvocationSetting.html) 物件：

```
"elicitationCodeHook": {
    "enableCodeHookInvocation": boolean,
    "invocationLabel": string
}
```
+ 將 `enableCodeHookInvocation` Amazon Lex V2 `true` 的欄位變更為 ，以允許程式碼掛鉤正常執行。如果您標記 `false`，Amazon Lex V2 就像程式碼掛鉤成功傳回一樣。
+ `invocationLabel` 指出從中叫用程式碼掛鉤的對話方塊步驟。

## fulfillmentCodeHook
<a name="lambda-fulfillment-code-hook"></a>

`fulfillmentCodeHook` 欄位定義要執行的程式碼掛鉤設定，以滿足意圖。它映射到下列 [FulfillmentCodeHookSettings](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentCodeHookSettings.html) 物件：

```
"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)
}
```
+ 將 `active` Amazon Lex V2 `true` 的欄位變更為 ，以在對話中的該時間點呼叫程式碼掛勾。
+ 將 `enabled` Amazon Lex V2 `true` 的欄位變更為 ，以允許程式碼掛鉤正常執行。如果您標記 `false`，Amazon Lex V2 就像程式碼掛鉤成功傳回一樣。
+ 使用 `fulfillmentUpdatesSpecification` 欄位來指定在滿足意圖期間顯示來更新使用者的訊息，以及與其相關聯的時間。
+ 使用 `postFulfillmentStatusSpecification` 欄位指定程式碼掛鉤成功、失敗或逾時後發生的訊息和動作。

您可以將 `active`和`enableCodeHookInvocation`/`enabled` 欄位設定為 ，在對話中的下列時間點叫用 Lambda 程式碼掛勾`true`：

## 在初始回應期間
<a name="lambda-hook-initial-response"></a>

若要在辨識意圖後於初始回應中叫用 Lambda 函數，請在 [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) 或 [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) 操作的 `initialResponse` 欄位中使用 `codeHook`結構。`initialResponse` 欄位對應至下列 [InitialResponseSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_InitialResponseSetting.html) 物件：

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

## 槽引出後或在槽重新引出期間
<a name="lambda-hook-elicit-slot"></a>

若要在引出槽值後叫用 Lambda 函數，請使用 [CreateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateSlot.html) 或 [UpdateSlot](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateSlot.html) 操作的 `valueElicitation` 欄位中的 `slotCaptureSetting` 欄位。`slotCaptureSetting` 欄位對應至下列 [SlotCaptureSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_SlotCaptureSetting.html) 物件：

```
"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)
}
```
+ 若要在槽引出成功後叫用 Lambda 函數，請使用 `codeHook` 欄位。
+ 若要在槽引出失敗且 Amazon Lex V2 嘗試重試槽引出後叫用 Lambda 函數，請使用 `elicitationCodeHook` 欄位。

## 意圖確認或拒絕之後
<a name="lambda-hook-confirm-intent"></a>

若要在確認意圖時叫用 Lambda 函數，請使用 [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) 或 [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) 操作`intentConfirmationSetting`的 欄位。`intentConfirmation` 欄位對應至下列 [IntentConfirmationSetting](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_IntentConfirmationSetting.html) 物件：

```
"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)
}
```
+ 若要在使用者確認意圖及其插槽後叫用 Lambda 函數，請使用 `codeHook` 欄位。
+ 若要在使用者拒絕意圖確認且 Amazon Lex V2 嘗試重試槽引出後叫用 Lambda 函數，請使用 `elicitationCodeHook` 欄位。

## 在意圖履行期間
<a name="lambda-hook-fulfill-intent"></a>

若要叫用 Lambda 函數以滿足意圖，請使用 [CreateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_CreateIntent.html) 或 [UpdateIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_UpdateIntent.html) 操作中的 `fulfillmentCodeHook` 欄位。`fulfillmentCodeHook` 欄位對應至下列 [FulfillmentCodeHookSettings](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_FulfillmentCodeHookSettings.html) 物件：

```
{
    "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. 設定叫用 Lambda 函數的對話階段後，請使用 `BuildBotLocale`操作來重建機器人，以測試函數。

# 使用 CloudWatch Logs 日誌對 Lambda 函數進行偵錯
<a name="lambda-debug"></a>

[Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 是追蹤 API 呼叫和指標的工具，可用來協助偵錯 Lambda 函數。當您在主控台或使用 API 呼叫測試機器人時，CloudWatch 會記錄對話的每個步驟。如果您在 Lambda 程式碼中使用列印函數，CloudWatch 也會顯示該函數。

**檢視 Lambda 函數的 CloudWatch 日誌**

1. 請登入 AWS 管理主控台，開啟位於 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 的 CloudWatch 主控台。

1. 在左側列的**日誌**功能表下，選取**日誌群組**。

1. 選取您的 Lambda 函數日誌群組，其格式應為 `/aws/lambda/function-name`。

1. **日誌串流**清單包含具有機器人的每個工作階段的日誌。選擇要檢視的日誌串流。

1. 在**日誌事件**清單中，選取**時間戳記**旁的向右箭頭，以展開該事件的詳細資訊。從 Lambda 程式碼列印的任何內容都會顯示為日誌事件。使用此資訊來偵錯您的程式碼。

1. 偵錯程式碼後，請記得**部署** Lambda 函數，如果您使用主控台，則在重新測試機器人的行為之前重新載入**測試**視窗。