

支援終止通知：2025 年 9 月 15 日， AWS 將停止對 Amazon Lex V1 的支援。2025 年 9 月 15 日之後，您將無法再存取 Amazon Lex V1 主控台或 Amazon Lex V1 資源。如果您使用的是 Amazon Lex V2，請改參閱 [Amazon Lex V2 指南](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html)。

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

# 使用 Lambda 函數
<a name="using-lambda"></a>

您可以建立 AWS Lambda 函數以用作 Amazon Lex 機器人的程式碼掛鉤。您可以識別 Lambda 函數，以在意圖組態中執行初始化和驗證、履行或兩者。

我們建議您使用 Lambda 函數做為機器人的程式碼掛勾。如果沒有 Lambda 函數，您的機器人會將意圖資訊傳回至用戶端應用程式以進行履行。



**Topics**
+ [Lambda 函數輸入事件和回應格式](lambda-input-response-format.md)
+ [Amazon Lex 和 AWS Lambda 藍圖](lex-lambda-blueprints.md)

# Lambda 函數輸入事件和回應格式
<a name="lambda-input-response-format"></a>

本節說明 Amazon Lex 提供給 Lambda 函數的事件資料結構。使用此資訊來剖析 Lambda 程式碼中的輸入。它也會說明 Amazon Lex 預期 Lambda 函數傳回的回應格式。

**Topics**
+ [輸入事件格式](#using-lambda-input-event-format)
+ [回應格式](#using-lambda-response-format)

## 輸入事件格式
<a name="using-lambda-input-event-format"></a>

以下顯示傳遞給 Lambda 函數的 Amazon Lex 事件的一般格式。當您撰寫 Lambda 函數時，請使用此資訊。

**注意**  
即使 `messageVersion` 中沒有對應的變更，輸入格式也可能變更。如果出現新欄位，您的程式碼不應擲出錯誤。

```
{
  "currentIntent": {
    "name": "intent-name",
    "nluIntentConfidenceScore": score,
    "slots": {
      "slot name": "value",
      "slot name": "value"
    },
    "slotDetails": {
      "slot name": {
        "resolutions" : [
          { "value": "resolved value" },
          { "value": "resolved value" }
        ],
        "originalValue": "original text"
      },
      "slot name": {
        "resolutions" : [
          { "value": "resolved value" },
          { "value": "resolved value" }
        ],
        "originalValue": "original text"
      }
    },
    "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)"
  },
  "alternativeIntents": [
    {
      "name": "intent-name",
      "nluIntentConfidenceScore": score,
      "slots": {
        "slot name": "value",
        "slot name": "value"
      },
      "slotDetails": {
        "slot name": {
          "resolutions" : [
            { "value": "resolved value" },
            { "value": "resolved value" }
          ],
          "originalValue": "original text"
        },
        "slot name": {
          "resolutions" : [
            { "value": "resolved value" },
            { "value": "resolved value" }
          ],
          "originalValue": "original text"
        }
      },
      "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)"
    }
  ],
  "bot": {
    "name": "bot name",
    "alias": "bot alias",
    "version": "bot version"
  },
  "userId": "User ID specified in the POST request to Amazon Lex.",
  "inputTranscript": "Text used to process the request",
  "invocationSource": "FulfillmentCodeHook or DialogCodeHook",
  "outputDialogMode": "Text or Voice, based on ContentType request header in runtime API request",
  "messageVersion": "1.0",
  "sessionAttributes": { 
     "key": "value",
     "key": "value"
  },
  "requestAttributes": { 
     "key": "value",
     "key": "value"
  },
  "recentIntentSummaryView": [
    {
        "intentName": "Name",
        "checkpointLabel": Label,
        "slots": {
          "slot name": "value",
          "slot name": "value"
        },
        "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)",
        "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close",
        "fulfillmentState": "Fulfilled or Failed",
        "slotToElicit": "Next slot to elicit"
    }
  ],
   "sentimentResponse": { 
      "sentimentLabel": "sentiment",
      "sentimentScore": "score"
   },
   "kendraResponse": {
       Complete query response from Amazon Kendra
   },
   "activeContexts": [
        {
            "timeToLive": {
                "timeToLiveInSeconds": seconds,
                "turnsToLive": turns
            },
            "name": "name",
            "parameters": {
                "key name": "value"
            }
        }
    ]
}
```

請注意以下有關事件欄位的更多資訊：
+ **currentIntent** – 提供意圖 `name`、`slots` `slotDetails` 和 `confirmationStatus` 欄位。

   

  `nluIntentConfidenceScore` 是 Amazon Lex 認為目前意圖最符合使用者目前意圖的可信度。

   

  `slots` 是針對意圖設定的槽名稱對應至 Amazon Lex 在使用者對話中辨識的槽值。槽值會保持 null，直到使用者提供值為止。

   

  輸入事件中的槽值可能不符合為槽所設定的其中一個值。例如，如果使用者回應提示「您想要什麼顏色的汽車？」 搭配「pizza」，Amazon Lex 將傳回「pizza」做為槽值。您的函數應該驗證值，以確保內容符合邏輯。

   

  `slotDetails` 會提供有關槽值的更多資訊。`resolutions` 陣列包含為槽所識別的其他值清單。每個槽最多可有 5 個值。

   

  `originalValue` 欄位包含使用者為槽輸入的值。當槽類型設定為傳回最常用的解析值來做為槽值時，`originalValue` 可能與 `slots` 欄位中的值不同。

   

  `confirmationStatus` 提供對確認提示 (如果有的話) 的使用者回應。例如，如果 Amazon Lex 詢問「您想要訂購大型起司比薩嗎？」，取決於使用者回應，此欄位的值可以是 `Confirmed`或 `Denied`。否則，此欄位的值會式 `None`。

   

  如果使用者確認意圖，Amazon Lex 會將此欄位設定為 `Confirmed`。如果使用者拒絕意圖，Amazon Lex 會將此值設定為 `Denied`。

   

  在確認回應中，使用者表達用語可能會提供槽更新。例如，使用者可能說「是，大小改為中型。」 在此情況下，後續 Lambda 事件具有更新的槽值，`PizzaSize`設定為 `medium`。Amazon Lex 會將 `confirmationStatus`設定為 `None`，因為使用者修改了一些槽資料，要求 Lambda 函數執行使用者資料驗證。

   
+ **alternativeIntents** – 如果您啟用可信度分數，Amazon Lex 最多會傳回四個替代意圖。每個意圖都包含一個分數，指出 Amazon Lex 根據使用者的表達用語，認為意圖是正確意圖的可信度。

   

  替代意圖的內容與 `currentIntent` 欄位的內容相同。如需詳細資訊，請參閱[使用可信度分數](confidence-scores.md)。

   
+ **bot** – 處理請求之機器人的相關資訊。
  + `name` – 處理請求的機器人名稱。
  + `alias` – 處理請求的機器人版本別名。
  + `version` – 處理請求的機器人版本。

   
+ **userId** – 此值由用戶端應用程式提供。Amazon Lex 會將它傳遞給 Lambda 函數。

   
+ **inputTranscript** – 用來處理請求的文字。

  如果輸入是文字，`inputTranscript` 欄位會包含使用者輸入的文字。

   

  如果輸入是音訊串流，`inputTranscript` 欄位會包含從音訊串流擷取的文字。這是實際處理以識別意圖和槽值的文字。

   
+ **invocationSource** – 若要指出 Amazon Lex 調用 Lambda 函數的原因，它會將此設定為下列其中一個值：
  + `DialogCodeHook` – Amazon Lex 會設定此值來指示 Lambda 函數初始化函數，並驗證使用者的資料輸入。

     

    當意圖設定為調用 Lambda 函數做為初始化和驗證程式碼掛勾時，Amazon Lex 會在 Amazon Lex 了解意圖之後，在每個使用者輸入 （表達式） 上調用指定的 Lambda 函數。
**注意**  
如果意圖不明確，Amazon Lex 無法叫用 Lambda 函數。

     
  + `FulfillmentCodeHook` – Amazon Lex 會設定此值來指示 Lambda 函數實現意圖。

     

    如果意圖設定為調用 Lambda 函數做為履行程式碼掛勾，Amazon Lex 只會在擁有所有槽資料以滿足意圖之後，才會將 `invocationSource` 設定為此值。

     

  在您的意圖組態中，您可以有兩個單獨的 Lambda 函數來初始化和驗證使用者資料，以及實現意圖。您也可以使用一個 Lambda 函數來執行兩者。在這種情況下，您的 Lambda 函數可以使用 `invocationSource`值來遵循正確的程式碼路徑。

    
+ **outputDialogMode** – 對於每個使用者輸入，用戶端會使用其中一個執行時間 API 操作，[PostContent](API_runtime_PostContent.md)或 ，將請求傳送至 Amazon Lex[PostText](API_runtime_PostText.md)。Amazon Lex 使用請求參數來判斷對用戶端的回應是文字還是語音，並相應地設定此欄位。

   

  Lambda 函數可以使用此資訊來產生適當的訊息。例如，如果用戶端預期語音回應，您的 Lambda 函數可能會傳回語音合成標記語言 (SSML)，而不是文字。

   
+ **messageVersion** – 訊息的版本，可識別進入 Lambda 函數的事件資料格式，以及來自 Lambda 函數的預期回應格式。
**注意**  
您在定義意圖時設定此值。在目前實作中，僅支援訊息版本 1.0。因此，主控台假設 1.0 的預設值，而且不會顯示訊息的版本。
+ **sessionAttributes** – 用戶端在請求中傳送的應用程式特定工作階段屬性。如果您希望 Amazon Lex 將它們包含在用戶端的回應中，您的 Lambda 函數應在回應中將這些函數傳回 Amazon Lex。如需詳細資訊，請參閱[設定工作階段屬性](context-mgmt-session-attribs.md)

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

   
+ **recentIntentSummaryView** – 意圖狀態的相關資訊。您可以查看最近使用之三個意圖的相關資訊。您可以使用此資訊來設定意圖中的值，或返回先前的意圖。如需詳細資訊，請參閱[使用 Amazon Lex API 管理工作階段](how-session-api.md)。

   
+ **sentimentResponse** – 最後表達用語的 Amazon Comprehend 情緒分析結果。您可以根據使用者表達的情緒，使用此資訊來管理機器人的對話流程。如需詳細資訊，請參閱[情緒分析](sentiment-analysis.md)。

   
+ **kendraResponse** – 查詢 Amazon Kendra 索引的結果。只會出現在履行程式碼掛勾的輸入中，以及只有在意圖延伸 `AMAZON.KendraSearchIntent` 內建意圖時才會出現。欄位包含來自 Amazon Kendra 搜尋的整個回應。如需詳細資訊，請參閱[AMAZON.KendraSearchIntent](built-in-intent-kendra-search.md)。

   
+ **activeContexts** – 與此使用者對話期間處於作用中狀態的一或多個內容。
  + **timeToLive** – 與使用者對話中內容保持作用中的時間長度或轉數。
  + **name** – 內容的名稱。
  + **參數** 的鍵/值對清單包含啟動內容之意圖的槽名稱和值。

  如需詳細資訊，請參閱[設定意圖內容](context-mgmt-active-context.md)。

## 回應格式
<a name="using-lambda-response-format"></a>

Amazon Lex 預期 Lambda 函數會以下列格式回應：

```
{
  "sessionAttributes": {
    "key1": "value1",
    "key2": "value2"
    ...
  },
  "recentIntentSummaryView": [
    {
       "intentName": "Name",
       "checkpointLabel": "Label",
       "slots": {
         "slot name": "value",
         "slot name": "value"
        },
       "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)",
        "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close",
        "fulfillmentState": "Fulfilled or Failed",
        "slotToElicit": "Next slot to elicit"
    }
  ],
  "activeContexts": [
     {
       "timeToLive": {
          "timeToLiveInSeconds": seconds,
          "turnsToLive": turns
      },
      "name": "name",
      "parameters": {
        "key name": "value"
      }
    }
  ],
  "dialogAction": {
    "type": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close",
    Full structure based on the type field. See below for details.
  }
}
```

回應包含四個欄位。`sessionAttributes`、 `recentIntentSummaryView`和 `activeContexts` 欄位為選用， `dialogAction` 欄位為必要欄位。`dialogAction` 欄位的內容取決於 `type` 欄位的值。如需詳細資訊，請參閱[dialogAction](#lambda-response-dialogAction)。

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

選用。如果您包含 `sessionAttributes` 欄位，它可以留空。如果您的 Lambda 函數未傳回工作階段屬性，則透過 API 或 Lambda 函數`sessionAttributes`傳遞的最後一個已知值會保留。如需詳細資訊，請參閱 [PostContent](API_runtime_PostContent.md) 和 [PostText](API_runtime_PostText.md) 操作。

```
  "sessionAttributes": { 
     "key1": "value1",
     "key2": "value2"
  }
```

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

選用。如果包含，則設定一個或更多最近的意圖的值。您最多可以包含三個意圖的資訊。例如，您可以根據目前意圖所蒐集的資訊設定先前意圖的值。摘要中的資訊必須適用於該意圖。例如，意圖名稱必須是機器人中的意圖。如果要在摘要檢視中包含槽值，該槽必須存在於意圖中。如果沒有在回應中包含 `recentIntentSummaryView`，最近意圖的所有值仍會保持不變。如需詳細資訊，請參閱 [PutSession](API_runtime_PutSession.md) 操作或 [IntentSummary](API_runtime_IntentSummary.md) 資料類型。

```
"recentIntentSummaryView": [
    {
       "intentName": "Name",
       "checkpointLabel": "Label",
       "slots": {
         "slot name": "value",
         "slot name": "value"
        },
       "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)",
        "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close",
        "fulfillmentState": "Fulfilled or Failed",
        "slotToElicit": "Next slot to elicit"
    }
  ]
```

### activeContexts
<a name="lambda-response-context"></a>

選用。如果包含，請設定一或多個內容的值。例如，您可以包含內容，讓一或多個意圖將該內容做為輸入，在對話的下一個回合中符合辨識資格。

回應中未包含的任何作用中內容都會減少其time-to-live並且可能仍在下次請求時處於作用中狀態。

如果您為輸入事件中包含的內容指定time-to-live，則其將在下次請求時處於非作用中狀態。

如需詳細資訊，請參閱[設定意圖內容](context-mgmt-active-context.md)。

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

必要. `dialogAction` 欄位會引導 Amazon Lex 進行下一個動作，並說明在 Amazon Lex 將回應傳回給用戶端後，使用者預期會發生的情況。

`type` 欄位會指出後續動作，它也會決定 Lambda 函數需要作為`dialogAction`值的一部分提供的其他欄位。
+ `Close` — 通知 Amazon Lex 不要預期來自使用者的回應。例如，「您訂購的比薩已下單」不需要回應。

   

  `fulfillmentState` 欄位是必要的。Amazon Lex 使用此值來設定 中的 `dialogState` 欄位[PostContent](API_runtime_PostContent.md)或對用戶端應用程式的[PostText](API_runtime_PostText.md)回應。`message` 和 `responseCard` 欄位是選用的。如果您未指定訊息，Amazon Lex 會使用為意圖設定的再見訊息或後續訊息。

  ```
  "dialogAction": {
      "type": "Close",
      "fulfillmentState": "Fulfilled or Failed",
      "message": {
        "contentType": "PlainText or SSML or CustomPayload",
        "content": "Message to convey to the user. For example, Thanks, your pizza has been ordered."
      },
     "responseCard": {
        "version": integer-value,
        "contentType": "application/vnd.amazonaws.card.generic",
        "genericAttachments": [
            {
               "title":"card-title",
               "subTitle":"card-sub-title",
               "imageUrl":"URL of the image to be shown",
               "attachmentLinkUrl":"URL of the attachment to be associated with the card",
               "buttons":[ 
                   {
                      "text":"button-text",
                      "value":"Value sent to server on button click"
                   }
                ]
             } 
         ] 
       }
    }
  ```
+ `ConfirmIntent` — 通知 Amazon Lex 使用者應該提供是或否的答案，以確認或拒絕目前的意圖。

   

  您必須包含 `intentName` 與 `slots` 欄位。針對指定的意圖所填入的每個槽，`slots` 欄位都必須包含項目。您不需要為未填入的槽 `slots` 欄位中包含項目。​ 如果意圖的 `message` 欄位為空值，您必須為納入 `confirmationPrompt` 欄位。Lambda 函數傳回`message`的欄位內容優先於意圖中`confirmationPrompt`指定的 。此 `responseCard` 欄位為選用。

  ```
  "dialogAction": {
      "type": "ConfirmIntent",
      "message": {
        "contentType": "PlainText or SSML or CustomPayload",
        "content": "Message to convey to the user. For example, Are you sure you want a large pizza?"
      },
     "intentName": "intent-name",
     "slots": {
        "slot-name": "value",
        "slot-name": "value",
        "slot-name": "value"  
     },
     "responseCard": {
        "version": integer-value,
        "contentType": "application/vnd.amazonaws.card.generic",
        "genericAttachments": [
            {
               "title":"card-title",
               "subTitle":"card-sub-title",
               "imageUrl":"URL of the image to be shown",
               "attachmentLinkUrl":"URL of the attachment to be associated with the card",
               "buttons":[ 
                   {
                      "text":"button-text",
                      "value":"Value sent to server on button click"
                   }
                ]
             } 
         ] 
       }
    }
  ```
+ `Delegate` — 指示 Amazon Lex 根據機器人組態選擇下一個動作。如果回應不包含任何工作階段屬性，Amazon Lex 會保留現有的屬性。如果您希望槽值為空，您就不需在請求中包含槽欄位。如果您的履行函數沒有移除任何槽就傳回 `DependencyFailedException` 對話方塊動作，您將收到 `Delegate` 例外狀況。

  `kendraQueryRequestPayload` 和 `kendraQueryFilterString` 欄位是選用的，只有當意圖是從 `AMAZON.KendraSearchIntent` 內建意圖衍生而來時才會使用。如需詳細資訊，請參閱[AMAZON.KendraSearchIntent](built-in-intent-kendra-search.md)。

  ```
    "dialogAction": {
     "type": "Delegate",
     "slots": {
        "slot-name": "value",
        "slot-name": "value",
        "slot-name": "value"  
     },
     "kendraQueryRequestPayload": "Amazon Kendra query",
     "kendraQueryFilterString": "Amazon Kendra attribute filters"
    }
  ```
+ `ElicitIntent` — 通知 Amazon Lex 使用者應該回應包含意圖的表達用語。例如，「我想要大型比薩。」，亦即指出 `OrderPizzaIntent`。另一方面，表達用語「大」不足以讓 Amazon Lex 推斷使用者的意圖。

   

  `message` 和 `responseCard` 欄位是選用的。如果您未提供訊息，Amazon Lex 會使用其中一個機器人的釐清提示。如果未定義釐清提示，Amazon Lex 會傳回 400 錯誤的請求例外狀況。

  ```
  {
    "dialogAction": {
      "type": "ElicitIntent",
      "message": {
        "contentType": "PlainText or SSML or CustomPayload",
        "content": "Message to convey to the user. For example, What can I help you with?"
      },
      "responseCard": {
        "version": integer-value,
        "contentType": "application/vnd.amazonaws.card.generic",
        "genericAttachments": [
            {
               "title":"card-title",
               "subTitle":"card-sub-title",
               "imageUrl":"URL of the image to be shown",
               "attachmentLinkUrl":"URL of the attachment to be associated with the card",
               "buttons":[ 
                   {
                      "text":"button-text",
                      "value":"Value sent to server on button click"
                   }
                ]
             } 
         ] 
      }
   }
  ```
+ `ElicitSlot` — 通知 Amazon Lex 預期使用者會在回應中提供槽值。

   

  `intentName`、`slotToElicit` 和 `slots` 欄位是必要的。`message` 和 `responseCard` 欄位是選用的。如果您未指定訊息，Amazon Lex 會使用針對插槽設定的其中一個槽引出提示。

  ```
    "dialogAction": {
      "type": "ElicitSlot",
      "message": {
        "contentType": "PlainText or SSML or CustomPayload",
        "content": "Message to convey to the user. For example, What size pizza would you like?"
      },
     "intentName": "intent-name",
     "slots": {
        "slot-name": "value",
        "slot-name": "value",
        "slot-name": "value"  
     },
     "slotToElicit" : "slot-name",
     "responseCard": {
        "version": integer-value,
        "contentType": "application/vnd.amazonaws.card.generic",
        "genericAttachments": [
            {
               "title":"card-title",
               "subTitle":"card-sub-title",
               "imageUrl":"URL of the image to be shown",
               "attachmentLinkUrl":"URL of the attachment to be associated with the card",
               "buttons":[ 
                   {
                      "text":"button-text",
                      "value":"Value sent to server on button click"
                   }
                ]
             } 
         ] 
       }
    }
  ```

# Amazon Lex 和 AWS Lambda 藍圖
<a name="lex-lambda-blueprints"></a>

Amazon Lex 主控台提供預先設定的範例機器人 （稱為機器人藍圖），讓您可以在主控台中快速建立和測試機器人。對於這些機器人藍圖，也會提供 Lambda 函數藍圖。這些藍圖提供的範本程式碼可與其與對應的機器人搭配運作。您可以使用這些藍圖快速建立以 Lambda 函數做為程式碼掛勾設定的機器人，並測試end-to-end設定，而不必撰寫程式碼。

您可以使用下列 Amazon Lex 機器人藍圖和對應的 AWS Lambda 函數藍圖做為機器人的程式碼掛勾：
+ Amazon Lex 藍圖 — `OrderFlowers`
  + AWS Lambda 藍圖 — `lex-order-flowers-python`
+ Amazon Lex 藍圖 — `ScheduleAppointment` 
  + AWS Lambda 藍圖 — `lex-make-appointment-python`
+ Amazon Lex 藍圖 — `BookTrip`
  + AWS Lambda 藍圖 — `lex-book-trip-python`

若要使用藍圖建立機器人，並將其設定為使用 Lambda 函數做為程式碼掛勾，請參閱 [練習 1：使用藍圖建立 Amazon Lex 機器人 （主控台）](gs-bp.md)。如需使用其他藍圖的範例，請參閱[其他範例：建立 Amazon Lex 機器人](additional-exercises.md)。

## 更新特定地區設定的藍圖
<a name="blueprint-update-locale"></a>

如果您在英文 (US) (en-US) 以外的地區使用藍圖，則需要更新任何意圖的名稱，以包含地區設定。例如，如果您使用`OrderFlowers`藍圖，則需要執行下列動作。
+ 尋找靠近 Lambda `dispatch`函數程式碼結尾的函數。
+ 在 `dispatch`函數中，更新意圖的名稱，以包含您正在使用的地區設定。例如，如果您使用的是英文 （澳洲） (en-AU) 地區設定，請變更行：

  `if intent_name == 'OrderFlowers':`

  至

  `if intent_name == 'OrderFlowers_enAU':`

其他藍圖使用其他意圖名稱，應該在使用前如上述進行更新。