使用 AWS CloudFormation 模板管理 Amazon Lex 机器人
关键要点
Amazon Lex 是一种全面管理的人工智能服务,允许设计、构建和部署对话界面。利用 AWS CloudFormation,用户可以创建定义机器人及其依赖资源的模板,降低部署中的人为错误风险。通过模板管理 Amazon Lex 机器人可带来一致性、版本控制、可重用性等诸多好处。本文将指导您逐步创建 Amazon Lex V2 机器人的 CloudFormation 模板。在这篇文章中,我们将介绍如何使用 AWS CloudFormation 管理 Amazon Lex 机器人及其相关资源。通过这种方法,您可以轻松创建和维护聊天机器人,提高开发效率,降低潜在错误。
解决方案概述
我们将以 Book Trip 机器人为基础开始本次练习。我们将使用 CloudFormation 模板从零开始创建一个新机器人,包括定义意图、槽位及其他所需组件。此外,我们还将探讨版本控制、别名、集成 AWS Lambda 函数、创建条件分支和启用日志记录等主题。
前提条件
您需要具备以下前提条件:
一个 AWS 账户 以创建和部署 CloudFormation 模板创建 AWS CloudFormation 和执行模板中资源的所需 IAM 权限对 Amazon Lex、Lambda 函数及相关服务的基本知识对创建和部署 CloudFormation 模板的基本知识创建 IAM 角色
首先,您需要创建一个 IAM 角色供机器人使用。您可以通过初始化 CloudFormation 模板并将 IAM 角色作为资源添加实现。使用以下模板创建该角色。如果您下载示例模板并进行部署,您将看到一个 IAM 角色已被创建。我们将在文章中提供多个模板示例并逐步整合它们。
小熊加速器免费一小时yamlAWSTemplateFormatVersion 20100909Transform AWSServerless20161031Description CloudFormation template for book hotel botResources # 1 机器人在运行时使用的 IAM 角色 BotRuntimeRole Type AWSIAMRole Properties AssumeRolePolicyDocument Version 20121017 Statement Effect Allow Principal Service lexv2amazonawscom Action stsAssumeRole Path / Policies PolicyName LexRuntimeRolePolicy PolicyDocument Version 20121017 Statement Effect Allow Action pollySynthesizeSpeech comprehendDetectSentiment Resource
配置 Amazon Lex 机器人
接下来,您需要添加机器人定义。以下是 Amazon Lex 机器人定义的 YAML 模板,您可以逐步构建必要组件:
yamlType AWSLexBotProperties AutoBuildBotLocales Boolean BotFileS3Location S3Location BotLocales BotLocale BotTags Tag DataPrivacy DataPrivacy Description String IdleSessionTTLInSeconds Integer Name String RoleArn String TestBotAliasSettings TestBotAliasSettings TestBotAliasTags Tag
为了创建仅包含机器人定义的机器人,而不包含意图,您可以使用以下模板,在此模板中指定机器人的名称、先前创建的角色 ARN、数据隐私设置等:
yamlBookHotelBot DependsOn BotRuntimeRole # 在上一步创建的角色 Type AWSLexBot Properties Name BookHotel Description Sample Bot to book a hotel RoleArn !GetAtt BotRuntimeRoleArn DataPrivacy ChildDirected false IdleSessionTTLInSeconds 300
您可以下载更新的模板。部署更新后的模板可让您创建角色和机器人的定义。请注意,您正在更新之前的堆栈。
最后一步是定义 BotLocales,这是机器人功能的主要组成部分,例如 Intents 和 Slot types。以下是 YAML 模板示例:
yaml CustomVocabulary CustomVocabulary Description String Intents Intent LocaleId String NluConfidenceThreshold Number SlotTypes SlotType VoiceSettings VoiceSettings
在本例中,您将构建 BookHotel 意图,并为房间类型设置一个自定义槽类型。接下来,您设置 LocaleId 和 VoiceSettings,然后添加 SlotTypes 及其对应的值。
接下来的步骤是定义 Intents,首先是 BookHotel 意图,涉及添加语句、槽位和槽位优先级。这些节点的详细信息将在提供的模板中展示。最后,您添加第二个意图,即 FallbackIntent。请参见以下代码:
yamlBotLocales LocaleId enUS Description en US locale NluConfidenceThreshold 040 VoiceSettings VoiceId Matthew SlotTypes Name RoomTypeValues Description Type of room SlotTypeValues SampleValue Value queen SampleValue Value king SampleValue Value deluxe ValueSelectionSetting ResolutionStrategy ORIGINALVALUE Intents Name BookHotel Description Intent to book a hotel room SampleUtterances Utterance Book a hotel Utterance I want a make hotel reservations Utterance Book a {Nights} night stay in {Location} IntentConfirmationSetting PromptSpecification MessageGroupsList Message PlainTextMessage Value Okay I have you down for a {Nights} night stay in {Location} starting {CheckInDate} Shall I book the reservation MaxRetries 3 AllowInterrupt false DeclinationResponse MessageGroupsList Message PlainTextMessage Value Okay I have cancelled your reservation in progress AllowInterrupt false SlotPriorities Priority 1 SlotName Location Priority 2 SlotName CheckInDate Priority 3 SlotName Nights Priority 4 SlotName RoomType Slots Name Location Description Location of the city in which the hotel is located SlotTypeName AMAZONCity ValueElicitationSetting SlotConstraint Required PromptSpecification MessageGroupsList Message PlainTextMessage Value What city will you be staying in MaxRetries 2 AllowInterrupt false Name CheckInDate Description Date of checkin SlotTypeName AMAZONDate ValueElicitationSetting SlotConstraint Required PromptSpecification MessageGroupsList Message PlainTextMessage Value What day do you want to check in MaxRetries 2 AllowInterrupt false Name Nights Description number of nights SlotTypeName AMAZONNumber ValueElicitationSetting SlotConstraint Required PromptSpecification MessageGroupsList Message PlainTextMessage Value How many nights will you be staying MaxRetries 2 AllowInterrupt false Name RoomType Description Enumeration of types of rooms offered by hotel SlotTypeName RoomTypeValues ValueElicitationSetting SlotConstraint Required PromptSpecification MessageGroupsList Message PlainTextMessage Value What type of room would you like queen king or deluxe MaxRetries 2 AllowInterrupt false Name FallbackIntent Description Default intent when no other intent matches ParentIntentSignature AMAZONFallbackIntent
您可以下载 CloudFormation 模板以获取当前为止的所有工作。在使用此模板更新您的堆栈后,将部署一个功能齐全的机器人。在 Amazon Lex 控制台,您可以确认有一个草稿版本的机器人,且已创建一个名称为 TestBotAlias 的默认别名。
创建新的机器人版本和别名
Amazon Lex 支持发布机器人的 版本、意图和槽类型,以便控制客户端应用的实现。版本是机器人定义的编号快照,可以在工作流的不同部分发布以供使用,例如开发、测试和生产。Amazon Lex 机器人还支持 别名,别名是指向特定版本机器人的指针。通过别名,您可以更新客户端应用的版本。在实际场景中,机器人别名用于蓝绿部署和管理特定于环境的配置,如开发和生产环境。
例如,假设您将别名指向机器人的版本 1。当需要更新机器人时,您可以发布版本 2 并将别名指向新版本。由于您的应用使用的是别名而不是特定版本,所有客户端均可无缝获取新功能,而无需进行更新。
请注意,当您更改 CloudFormation 模板并启动部署时,所做的更改将应用于草稿版本,主要用于测试。完成测试阶段后,您可以创建新版本以最终确定所做的更改。
接下来,您根据草稿创建新机器人的版本,设置新的别名,并将版本链接到该别名。以下是两个新的资源示例,需要添加到您的模板中:
yamlBookHotelInitialVersion DependsOn BookHotelBot Type AWSLexBotVersion Properties BotId !Ref BookHotelBot BotVersionLocaleSpecification LocaleId enUS BotVersionLocaleDetails SourceBotVersion DRAFT Description Hotel Bot initial version
BookHotelDemoAlias Type AWSLexBotAlias Properties BotId !Ref BookHotelBot BotAliasName BookHotelDemoAlias BotVersion !GetAtt BookHotelInitialVersionBotVersion
您可以下载新版本模板,通过更新堆栈进行部署。在 Amazon Lex 控制台中,您可以看到创建了新版本,并与名为 BookHotelDemoAlias 的新别名相关联。
当您创建新的 Amazon Lex 机器人版本时,版本号通常会按顺序递增,从 1 开始。要区分特定版本,您可以参考其描述。
添加 Lambda 函数
要初始化值或验证用户输入,您可以将 Lambda 函数作为代码钩子添加到机器人中。同时,您也可以使用 Lambda 函数进行执行,例如向数据库写入数据或调用 API 以保存收集到的信息。有关更多信息,请参考使用 AWS Lambda 函数启用自定义逻辑。
让我们在 CloudFormation 模板中为 Lambda 函数添加一个新资源。虽然通常不建议在 CloudFormation 模板中嵌入代码,但出于简化演示部署的目的,我们这里这样做。以下是代码示例:
yamlHotelBotFunction DependsOn BotRuntimeRole # 在机器人部署之前确保 Lambda 函数已准备就绪 Type AWSServerlessFunction Properties FunctionName bookhotellambda Runtime python311 Timeout 15 Handler indexlambdahandler InlineCode import os import json
def close(intentrequest) intentrequest[sessionState][intent][state] = Fulfilled message = {contentType PlainText content Your Booking is confirmed} sessionattributes = {} sessionState = intentrequest[sessionState] if sessionAttributes in sessionState sessionattributes = sessionState[sessionAttributes] requestAttributes = None if requestAttributes in intentrequest requestAttributes = intentrequest[requestAttributes] return { sessionState { sessionAttributes sessionattributes dialogAction { type Close } intent intentrequest[sessionState][intent] originatingRequestId xxxxxxxxxxxxxxxxxxx } messages [message] sessionId intentrequest[sessionId] requestAttributes requestAttributes } def router(event) intentname = event[sessionState][intent][name] slots = event[sessionState][intent][slots] if (intentname == BookHotel) # invoke lambda and return result return close(event) raise Exception( The intent is not supported by Lambda intentname) def lambdahandler(event context) response = router(event) return response要将此 Lambda 函数用于意图的执行,请在意图中启用代码钩子设置:
yamlIntents Name BookHotel Description Intent to book a hotel room FulfillmentCodeHook Enabled true SampleUtterances Utterance Book a hotel Utterance I want a make hotel reservations Utterance Book a {Nights} night stay in {Location}
由于对机器人的更改,您需要通过在模板中添加名为 BookHotelVersionWithLambda 的新资源来创建机器人新版本:
yamlBookHotelVersionWithLambda DependsOn BookHotelInitialVersion Type AWSLexBotVersion Properties BotId !Ref BookHotelBot BotVersionLocaleSpecification LocaleId enUS BotVersionLocaleDetails SourceBotVersion DRAFT Description Hotel Bot with a lambda function

Lambda 函数与机器人别名关联。每个语言的 Amazon Lex V2 每个别名只可以使用一个 Lambda 函数。因此,您需要在模板中更新别名,以添加 Lambda 函数资源。您可以在 BotAliasLocalSettings 部分中执行此操作。您还需将别名指向您创建的新版本。以下是修改后的别名配置示例:
yamlBookHotelDemoAlias Type AWSLexBotAlias Properties BotId !Ref BookHotelBot BotAliasName BookHotelDemoAlias BotVersion !GetAtt BookHotelVersionWithLambdaBotVersion BotAliasLocaleSettings LocaleId enUS BotAliasLocaleSetting Enabled true CodeHookSpecification LambdaCodeHook CodeHookInterfaceVersion 10 LambdaArn !GetAtt HotelBotFunctionArn
到目前为止,您仅将 Lambda 函数与别名链接。然而,您需要授予权限,以允许别名调用 Lambda 函数。在以下代码中,您为 Amazon Lex 添加了 Lambda 调用权限,并指定别名 ARN 作为源 ARN:
yamlLexInvokeLambdaPermission Type AWSLambdaPermission Properties Action lambdaInvokeFunction FunctionName !GetAtt HotelBotFunctionArn Principal lexv2amazonawscom SourceArn !GetAtt BookHotelDemoAliasArn
您可以下载最新版本的模板。通过使用此版本更新堆栈后,您将拥有一个与 Lambda 函数集成的 Amazon Lex 机器人。
![second version](https//d2908q01vom