

终止支持通知：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>

您可以创建用作您的 Amazon Lex 机器人的代码挂钩的 AWS Lambda 函数。您可以在您的意图配置中标识 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 在用户会话中识别出的插槽值的映射。槽值保持为空，直到用户提供一个值。

   

  输入事件中的槽值可能与为槽配置的值之一不匹配。例如，如果用户对“您想要什么颜色的车？”提示给出的响应是 “披萨”，Amazon Lex 会将“披萨”返回为插槽值。您的函数应对这些值进行验证，以确保它们在上下文中有意义。

   

  `slotDetails` 提供有关槽值的附加信息。`resolutions` 数组包含为槽识别的附加值的列表。每个槽最多可以有五个值。

   

  `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 操作之一向 Amazon Lex 发送请求，[PostContent](API_runtime_PostContent.md)或者[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** — 客户端在请求中发送的特定于请求的属性。可以使用请求属性传递不需要在整个会话中保留的信息。如果没有请求属性，该值将为空。有关更多信息，请参阅 [设置请求属性](context-mgmt-request-attribs.md)。

   
+ **recentIntentSummary查看**-有关意图状态的信息。您可以看到有关所用最后三个意图的信息。您可以使用此信息在意图中设置值或返回到之前的意图。有关更多信息，请参阅 [使用 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** — 上下文的名称。
  + **p** arameter key/value s 包含激活上下文的意图中插槽的名称和值的配对列表。

  有关更多信息，请参阅 [设置意图上下文](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"
  }
```

### recentIntentSummary查看
<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的上下文指定 a of 0，则该上下文将在下一个请求中处于非活动状态。

有关更多信息，请参阅 [设置意图上下文](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 使用此值在对客户端应用程序的 [PostContent](API_runtime_PostContent.md) 或 [PostText](API_runtime_PostText.md) 响应中设置 `dialogState` 字段。`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` 字段无需包含条目。如果目的的 `confirmationPrompt` 字段为空，则您必须包括 `message` 字段。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 将保留现有属性。如果您希望槽值为空，则无需在请求中包含槽字段。如果您的实现函数返回 `Delegate` 对话操作而没有删除任何槽，您将收到 `DependencyFailedException` 异常。

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

如果您在英语（美国）(en-US) 以外的区域设置中使用蓝图，则需要更新任何意图的名称以包含该区域设置。例如，如果您使用的是 `OrderFlowers` 蓝图，则需要执行以下操作。
+ 在 Lambda 函数代码末尾处找到 `dispatch` 函数。
+ 在 `dispatch` 函数中，更新意图的名称以包含您正在使用的区域设置。例如，如果您使用的是英语（澳大利亚）(en-AU) 区域设置，请更改以下行：

  `if intent_name == 'OrderFlowers':`

  修改为

  `if intent_name == 'OrderFlowers_enAU':`

其他蓝图使用其他意图名称，在使用它们之前，应按上述方式对其进行更新。