Étape 4 sur 6 - Environ 40 min
Lab 04 - Conversational AI: Lex V2
Build and test a chatbot with Amazon Lex V2.
Time: about 40 minutes.
Overview
Amazon Lex V2 builds conversational interfaces for text and voice. A bot has one or more locales (languages); each locale has intents (what the user wants), sample utterances (phrases that trigger an intent), and optional slots (values to collect, such as a date). Lex uses natural language understanding (NLU) to match what the user types or says to an intent, and Amazon Polly to speak the replies.
What gets created
| Component | Resources |
|---|---|
lex |
Bot ai_04_conversational_test_lex with locale en_US (voice Joanna, neural engine, NLU confidence threshold 0.40) |
Intents Greeting, Help, and ServiceInfo (plus the built-in FallbackIntent) |
|
Role ai-04-conversational-test-lex-role with Polly and CloudWatch Logs permissions |
|
CloudWatch log group /aws/lex/ai_04_conversational_test_lex (7-day retention) |
Lex bot names cannot contain dashes, so the component replaces them with
underscores. This lab has no S3 bucket or iam-role component.
The sample intents have no slots, so the bot builds without any custom slot types. Adding a slot is an optional exercise at the end of this guide.
Architecture
+---------------------------------------------------------------+
| User input |
| (text from the CLI or console, or voice) |
+-------------------------------+-------------------------------+
|
v
+---------------------------------------------------------------+
| Lex V2 bot, locale en_US |
| |
| +--------------+ +--------------+ +-----------------------+ |
| | Greeting | | Help | | ServiceInfo | |
| | "Hello" | | "Help me" | | "Tell me about AWS | |
| | "Hi" | | "What can | | AI services" | |
| | "Hey there" | | you do" | | "What AI services | |
| | | | | | does AWS offer" | |
| +--------------+ +--------------+ +-----------------------+ |
| |
| +----------------+ |
| | FallbackIntent | built in: input that matches no intent |
| +----------------+ |
| |
| Voice: Joanna (neural) through Amazon Polly |
| NLU confidence threshold: 0.40 |
+-------------------------------+-------------------------------+
|
v
+---------------------------------------------------------------+
| CloudWatch log group /aws/lex/ai_04_conversational_... |
+---------------------------------------------------------------+Before you start
Complete the Prerequisites in the README.
Deploy
The stack stacks/labs/04-conversational/test.yaml has one component, so
there is no apply order and no !terraform.output. It imports the lex
defaults from the catalog and sets the
bot's variables (locale, voice, NLU
threshold).
cd atmos-aws-ai-infra # the lab folder
# Check the stack
atmos validate stacks
atmos describe stacks -s lab-04-conversational-test --process-functions=false
atmos terraform apply lex -s lab-04-conversational-testSet shell variables
STACK=lab-04-conversational-test
BOT_ID=$(atmos terraform output lex -s $STACK --skip-init -- -raw bot_id)
echo "$BOT_ID"Build the bot
Terraform creates the bot definition in the DRAFT version. Lex must
build the locale before it can answer.
aws lexv2-models build-bot-locale \
--bot-id "$BOT_ID" \
--bot-version DRAFT \
--locale-id en_US \
--region us-east-1
# Repeat until the status is "Built" (usually under a minute)
aws lexv2-models describe-bot-locale \
--bot-id "$BOT_ID" \
--bot-version DRAFT \
--locale-id en_US \
--region us-east-1 \
--query botLocaleStatusBuild again whenever you change intents (in Terraform or in the console).
Test with the CLI
TSTALIASID is the built-in test alias. It always points to the DRAFT
version, so you can test without publishing.
Greeting
aws lexv2-runtime recognize-text \
--bot-id "$BOT_ID" \
--bot-alias-id TSTALIASID \
--locale-id en_US \
--session-id test-session-001 \
--text "Hello" \
--region us-east-1 \
--query '{reply:messages[0].content,intent:sessionState.intent.name,state:sessionState.intent.state}'{
"reply": "Hello! Welcome to the AI Lab assistant. How can I help you today?",
"intent": "Greeting",
"state": "Fulfilled"
}Help and ServiceInfo
for text in "What can you do?" "Tell me about AWS AI services" "Which AI service should I use on AWS?"; do
aws lexv2-runtime recognize-text \
--bot-id "$BOT_ID" --bot-alias-id TSTALIASID --locale-id en_US \
--session-id test-session-002 --text "$text" --region us-east-1 \
--query '[sessionState.intent.name, interpretations[0].nluConfidence.score]' --output text
doneThe last phrase is not a sample utterance. NLU still matches it to
ServiceInfo because it is close in meaning; the second column is the
confidence score.
Fallback
aws lexv2-runtime recognize-text \
--bot-id "$BOT_ID" --bot-alias-id TSTALIASID --locale-id en_US \
--session-id test-session-003 --text "asdfghjkl random text" --region us-east-1 \
--query 'sessionState.intent.name'Expect FallbackIntent: no intent reached the 0.40 confidence threshold.
Several turns in one session
Lex keeps state per --session-id. Send several messages with the same
session ID and look at sessionState in each reply:
for text in "Hi there" "I need help" "What AI services does AWS offer"; do
aws lexv2-runtime recognize-text \
--bot-id "$BOT_ID" --bot-alias-id TSTALIASID --locale-id en_US \
--session-id multi-turn-001 --text "$text" --region us-east-1 \
--query 'messages[0].content' --output text
doneConsole testing (optional)
- Open the Amazon Lex V2 console.
- Select the bot
ai_04_conversational_test_lex, then the English (US) locale, then Intents. - Choose Test. Type messages and open Inspect to see the matched intent, the confidence scores of the other intents, and the session state.
Publish a version and an alias (optional)
Applications should call a numbered version through an alias, not DRAFT.
These resources are created by the CLI, not Terraform, so delete them before
you destroy the bot (see Cleanup).
BOT_VERSION=$(aws lexv2-models create-bot-version \
--bot-id "$BOT_ID" \
--bot-version-locale-specification '{"en_US": {"sourceBotVersion": "DRAFT"}}' \
--region us-east-1 \
--query botVersion --output text)
# Repeat until "Available"
aws lexv2-models describe-bot-version \
--bot-id "$BOT_ID" --bot-version "$BOT_VERSION" \
--region us-east-1 --query botStatus
ALIAS_ID=$(aws lexv2-models create-bot-alias \
--bot-id "$BOT_ID" \
--bot-alias-name prod \
--bot-version "$BOT_VERSION" \
--region us-east-1 \
--query botAliasId --output text)
aws lexv2-runtime recognize-text \
--bot-id "$BOT_ID" --bot-alias-id "$ALIAS_ID" --locale-id en_US \
--session-id prod-001 --text "Hello" --region us-east-1 \
--query 'messages[0].content'Optional exercise: add a slot
To let ServiceInfo capture which service the user asks about:
- In the console, open the
en_USlocale and create a slot typeServiceNamewith values such as Rekognition, Textract, Comprehend, Translate, Transcribe, Polly, and Bedrock. - Add a slot
ServiceNameof that type to theServiceInfointent, and an utterance such asTell me about {ServiceName}. - Build the locale and test "Tell me about Polly". The reply's
sessionState.intent.slots.ServiceName.value.interpretedValueisPolly.
Changes made in the console are not in Terraform. The next
atmos terraform apply lex can revert the intent; to keep them, model the
slot type and slot in the lex component with aws_lexv2models_slot_type
and aws_lexv2models_slot.
Cleanup
If you created a version and alias, delete them first. They are not in the Terraform state, and deleting the bot can fail while an alias still points to a version.
aws lexv2-models delete-bot-alias --bot-id "$BOT_ID" --bot-alias-id "$ALIAS_ID" --region us-east-1
aws lexv2-models delete-bot-version --bot-id "$BOT_ID" --bot-version "$BOT_VERSION" --region us-east-1Then destroy the component:
atmos terraform destroy lex -s lab-04-conversational-testTroubleshooting
- ResourceNotFoundException or "bot locale not built" from
recognize-text- build the locale and wait forBuilt. - Every message goes to FallbackIntent - the locale was built before the
intents existed, or the build failed. Run
describe-bot-localeand checkfailureReasons, then build again. - Destroy fails because the bot is in use - delete the alias and the
version you created, then run
destroyagain.
Cost
Lex bills per text request and per speech request processed. A bot that nobody calls costs nothing; the log group stores data only if you turn on conversation logs. See Lex pricing. Free Tier terms depend on your account; see AWS Free Tier.
Next steps
- Previous: Lab 03 - Speech: Transcribe and Polly
- Next: Lab 05 - Generative AI: Bedrock and guardrails - foundation models, guardrails, and RAG on Amazon Bedrock.
- Back to the lab overview.
- Add a Lambda code hook for dynamic answers, or try the Lex generative AI features that use Bedrock to help design the bot.
Atmos docs
- Terraform Components in stacks - how the stack configures the single
lexcomponent. - Stack Catalogs - the
lexdefaults instacks/catalog/conversational/lex.yaml. - Configure Variables - change
nlu_confidence_thresholdorvoice_idin the lab stack. - atmos terraform plan - run it after console edits to see the drift Terraform would revert.
- atmos terraform output - reading
bot_id.
Exam connection
This lab practices:
- AIF-C01, Fundamentals of AI and ML - conversational AI and natural language understanding: intents, utterances, slots, confidence thresholds, and fallback handling with a managed service.
- AIF-C01, Applications of Foundation Models - knowing when a rule-and-intent chatbot is enough and when a foundation model (Lab 05) is a better fit.
- MLA-C01, Deployment and Orchestration of ML Workflows - building, versioning, and aliasing a bot so applications call a stable version.
- Terraform Associate (004), Implement and Maintain State - the drift that appears when you change resources outside Terraform (the console exercise), and resources the CLI creates that are not in the state (the version and alias).
- Terraform Associate (004), Read, Generate, and Modify Configuration - implicit dependencies through resource references (bot, then locale, then intents) and nested blocks.
Related certification pages: AIF-C01, MLA-C01, Terraform Associate (004).
Practice exam-style questions on these topics on CertLabPro: on the web at https://certlabpro.com/cert/aws-aif-c01, or in the app: https://certlabpro.com/mobile.