Save User Info with a Lex Chatbot

Get your chatbot to remember a user's personal details!

Introduction

⚑️ 30 second Summary

Welcome to Part FOUR of the Lex series!

In this five-project Lex series, you'll learn how to create a practical chatbot, BankerBot, that can help your imaginary bank's customers check their account balance and transfer money between accounts!

In your first three projects, you learnt how to:

  • πŸ’¬ Define intents
  • πŸ”€ Provide variations in your bot's responses
  • 🌟 Set up a custom slot type
  • 🀝 Connect your chatbot with AWS Lambda

You're on project FOUR πŸ€–πŸ€–πŸ€–πŸ€–

You'll learn how to set up context carryover, which is a technique that helps your chatbot remember things it's learnt about the user (like their birthday) from one intent and share them with other intents!

If you haven't done Project THREE yet, we'd recommend completing that project first.

Want a complete demo of how to do this project, from start to finish? Check out our 🎬 walkthrough with Maya 🎬

If you're up for a bit of a challenge, quiz yourself on the key concepts up ahead in this project.

This project is part of a series:

  1. Part 1: Build a Chatbot with Amazon Lex
  2. Part 2: Add Custom Slots to a Lex Chatbot
  3. Part 3: Connect Amazon Lex with Lambda

Before we start...

It's always good to understand exactly what you're here to do.

Set up a new Lex chatbot

To set up BankerBot for this project, we'll need to repeat the first three projects of this series.

Once you're all set up, you should have...

  • A new Lex chatbot called BankerBot.
  • WelcomeIntent set up.
  • FallbackIntent customised.
  • CheckBalance set up with your custom slot type called accountType.
  • Random bank balance figures returned to you when you check your balance (shoutout to Lambda).

We'll need to repeat the steps from the last two projects of this series to set up BankerBot's basic functionalities.

Have you completed Parts 1-3 of the Lex Series?

Yes, and I've deleted my bot

Perfect! Welcome back to the series, and it's awesome to have you here again. We'll need to repeat the steps from the last project of this series to set up BankerBot's basic functionalities.

πŸ”₯ Here's your mini challenge for this step... Try and recreate the bot you made in Parts 1-3.

Once you're all set up, you should have...

  • A new Lex chatbot called BankerBot.
  • WelcomeIntent set up.
  • FallbackIntent customised.
  • CheckBalance set up with your custom slot type called accountType.
  • Random bank balance figures returned to you when you check your balance (shoutout to Lambda).

You got this. Challenge yourself to complete this in less than 30 minutes. Now that you've done this before, you'll be a lot more familiar with the steps involved πŸ˜‰

Yes, and I have my bot

Wooh! Let's gooo! πŸ”₯

No, I haven't done it yet!

No worries - you're in good hands!

Once you're finished, you should have:

  • A new Lex chatbot called BankerBot.
  • WelcomeIntent set up.
  • FallbackIntent customised.
  • CheckBalance set up with your custom slot type called accountType.
  • Random bank balance figures returned to you when you check your balance (shoutout to Lambda).

Let's get started!

  • Log in to your AWS Account.
  • Navigate to Amazon Lex (type Lex into your console's search bar).
  • Check your URL in your web browser - does it say ...console.aws.amazon.com/lexv2/...?
    • If you're not seeing "lexv2" in your URL, click on Switch to the new Lex V2 console link in your left-hand menu.
  • Select Create bot.
  • Select Create a blank bot.

Can't find the Create a blank bot option?

You might need to select the Traditional tab first to see it.

If you're stuck, ask the NextWork community!

  • For Bot name, enter BankerBot
  • For Description, enter Banker Bot to help customer check their balance and make transfers.
  • Under IAM permissions, select Create a role with basic Amazon Lex permissions. We'll be using it to call Lambda later!
  • Under Children’s Online Privacy Protection Act (COPPA), select No.
  • Under Idle session timeout, keep the default of 5 minutes.
  • Select Next.
  • Keep the language as English so you can explore Lex's full set of features in this project.
  • Under Voice interaction, click on the dropdown that says Danielle.
  • Click around different voice options to choose your favorite one. Two favorites in the NextWork community are Gregory and Ruth :D
  • For Intent classification confidence score threshold, keep the default value of 0.40.

What is intent classification confidence score threshold?

When you're using Amazon Lex to build a chatbot, this threshold is like a minimum score for your chatbot to confidently understand what the user is trying to say

Setting this to 0.4 means that your chatbot needs to be at least 40% confident that it understands what the user is asking to be able to give a response

So if a user's input is ambiguous and your chatbot's confidence score is below 0.4, it'll throw an error message.

  • Select Done.

Set Up WelcomeIntent

  • When your bot is created, you will automatically see a page called Intent: NewIntent.

What are intents?

An intent is what the user is trying to achieve in their conversation with the chatbot. For example, checking a bank account balance; booking a flight; ordering food

In Amazon Lex, you build your chatbot by defining and categorising different intents. If you set up different intents, one single chatbot can manage a bunch of requests that are usually related to each other.

  • Under Intent details, enter WelcomeIntent for the Intent name.
  • Add the description Welcoming a user when they say hello.
  • Scroll down to the Sample utterances panel.
  • Click the Plain Text button.
  • Copy the text below, which represent the user inputs (called utterances) that will trigger this intent, and paste it into the text window:
Hi
Hello
I need help
Can you help me?
  • Scroll down to Closing response, and expand the arrow for Response sent to the user after the intent is fulfilled.
  • In the Message field, enter the following message: Hi! I'm BB, the Banking Bot. How can I help you today?
  • Choose Save intent.
  • Choose Build, which is close to the top of the screen.
  • This can take 30 seconds - time for a stretch!
  • Choose Test.
  • The following dialog will pop up, and you can interact with the bot by entering your opening message.
  • Try various different phrases and see what comes up. It's also a good way to check that you've set up your chatbot without any errors:
    • Help me
    • Hiya
    • How are you
    • Good morning

Manage FallbackIntent

  • In your left hand navigation panel, choose FallbackIntent.

What is FallbackIntent?

Remember the intent classification confidence score threshold, and how it's been set to 0.4?

If your chatbot has a confidence score below 40% for all the intents you've defined (in our case, it's just the WelcomeIntent for now), the FallbackIntent is triggered

Think of it as a custom error message that your chatbot will use to tell the user it doesn't understand their input.

  • The default FallbackIntent message you saw just now ("Intent FallbackIntent is fulfilled") can be a little confusing.
  • Let's re-phrase that message so it's clearer to the user that your chatbot doesn't understand the user's request.
  • Scroll down to Closing responses.
  • Expand the arrow for Response sent to the user after the intent is fulfilled.
  • In the Message field, add the following text:‍ Sorry I am having trouble understanding. Can you describe what you'd like to do in a few words? I can help you find your account balance, transfer funds and make a payment.
  • You'll notice another arrow next to the label Variations - optional.
  • Expand the arrow.
  • Enter the following text: Hmm could you try rephrasing that? I can help you find your account balance, transfer funds and make a payment.
  • Add another variation - what is another response that the chatbot could use to get clarification if it doesn't understand the user's intent?
  • Choose Save intent.
  • Choose Build - time for another stretch!
  • Choose Test.
  • Let's test 2-3 message that failed in your last try - what do you see now?

Create the accountType Custom Slot

  • In the Amazon Lex console, choose Slot types in your left hand navigation panel.

What are slots?

Slots are pieces of information that a chatbot needs to complete a user's request. Think of them as blanks that need to be filled in a form

For example, if the intent is to book a table at a restaurant, the chatbot needs specific details like: restaurant name, date, time, number of people

Amazon Lex provides many ready-to-use slot types for common information, like dates and times, but you can also create your own custom slot types to fit your specific needs. That's what we're about to do.

  • Choose Add slot type.
  • From the dropdown, choose Add blank slot type.
  • Enter accountType for the Slot type name.
  • Choose Add.
  • This will bring up a large Slot types editor panel.
  • In the Slot value resolution panel, choose Restrict to slot values.

What does this selection mean?

Selecting Restrict to slot values makes sure that only the values that you specify will count as a valid accountType!

Otherwise, Amazon Lex might use machine learning to accept other values that it frequently encounters from users.

In our case, we don't want Lex to use machine learning to accept other values. We have a set list of bank account types that we offer - Checking, Savings, and Credit accounts - and we don't offer any other bank account types.

If Lex starts accepting other values outside of these three, users could end up having conversations about bank account types we don't actually offer! To prevent that from happening, we'll restrict Lex to only acknowledge the bank account types we set up here.

  • Now let's add the three account types!
  • In the Values field, enter Checking
  • Select Add value, or just press Enter on your keyboard.
  • Do the same for Savings
  • Enter Credit, and add a few synonyms in the second field. Press ; on your keyboard after every time you add in a new one:
    • credit card
    • visa
    • mastercard
    • amex
    • american express
  • Choose Add value to finish up your work for Credit.
  • Choose Save slot type.

Create the CheckBalance intent

  • In your left hand navigation panel, head back to Intents.
  • Choose Add intent, then Add empty intent.
  • Enter CheckBalance as your intent name.
  • Choose Add.
  • Enter the following description in the Intent details panel: Intent to check the balance in the specified account type.
  • Scroll down to Sample utterances.
  • Switch to Plain Text and paste in the following utterances:
What’s the balance in my account?
Check my account balance
What’s the balance in my {accountType} account?
How much do I have in {accountType} ?
I want to check the balance
Can you help me with account balance?
Balance in {accountType}

Why do some of the utterances have the text {accountType}?

This means that Amazon Lex is now prepared to look for slot values from the user's input

If a word fits what's expected for the accountType slot, Lex will automatically fill in that information and won't need to prompt the user for their accountType anymore (saving time for the user)!

  • Scroll down until you can see the Slots pane.
  • Choose Add slot button.
  • For slot's Name, enter accountType
  • For the Slot type, choose your custom slot value accountType - which you created in Part 1!
  • Enter the following for Prompts: For which account would you like your balance?
  • Choose Add.
  • Choose Add slot again.
  • Use these values for your next slot:
    • Name: dateOfBirth
    • Slot type: AMAZON.Date
    • Prompts: For verification purposes, what is your date of birth?
  • Choose Save intent.
  • Choose Build - have you been stretching while you wait? πŸ‘€
  • Choose Test.
  • Now let's chat with your new chatbot! Enter I want to check my balance please.
  • Then, follow Amazon Lex's prompts and enter an account type and birth date.
  • Now choose Inspect near the top of your chat window.
  • Oooo, the chatbot has already filled both slots - accountType and dateOfBirth - with information it now knows about you.
  • In your chat window, now enter What's the balance in my savings account?
  • This time, Amazon Lex will only prompt you for your date of birth, as it already knows that it should be the Savings account it checks.
  • Nice - you've just validated that your chatbot is set up and ready for more!

Create Your AWS Lambda Function

  • Head to Lambda in your AWS Management Console.
  • Choose Author from scratch.
  • Function name - BankingBotEnglish
  • Runtime - Python 3.12, or a later version of Python3 if v3.12 is not available.
  • Select Create function.
  • Scroll down to the Function code section.
  • Double-click on lambda_function.py on the left-hand file browser.
  • Download the following source code file: ⬇️ BankingBotEnglish NextWork.py
  • Copy the downloaded code, and paste it in your text editor - it should completely replace any placeholder code that was in the example code fragment!
  • Choose Deploy, and your Lambda function is now all set up!

Connect AWS Lambda with Amazon Lex

  • Head back to your Amazon Lex console.
  • Select BankerBot.
  • On the left-hand menu, choose Aliases.

What are aliases, why are we using them?

Think of an alias in Amazon Lex as a pointer for a specific version of your bot

So when you're connecting Lex with other AWS services or your custom applications, those external resources will connect to an alias, which will point to the specific version of your bot that you want to use

Now, instead of always updating your apps to connect to the newest version of the bot, you can just update the alias to point to that new version. All your apps will automatically start using the updated bot without needing any changes on their end - this saves developers a TON of time and reduces the risk of errors!

  • Choose the default TestBotAlias.
  • From the Languages panel, select English (US).
  • Ooo how perfect - a Lambda function panel pops up. This panel lets you associate a Lambda function to this TestBotAlias version of your bot.
  • For Source, choose your Lambda function BankingBotEnglish.
  • Leave the Lambda function version or alias field at the default $LATEST.
  • Choose Save.

Connect your CheckBalance intent with your Lambda function

The Lambda function is now ready to work on the BankingBot intents βœ…, but we still have to tell Amazon Lex which intent will actually use the Lambda function.

Time to make a direct connection between a specific intent with the Lambda function!

  • Navigate to your CheckBalance intent.
  • Scroll down to Fulfillment panel.

What is fulfillment?

In Amazon Lex, fulfillment means completing the intent

With your BankingBot, after a user tells your bot:

  1. The account they want to check, and
  2. Their birthday for verification The bot has all the information it needs and moves to fulfillment. This is where it will use the Lambda function to get the account balance and pass it back to the user.
  • Expand the On successful fulfillment bubble.
  • Choose Advanced options.
  • Under the fulfillment Lambda code hook panel, check the checkbox next to Use a Lambda function for fulfillment.

What are code hooks?

Code hooks help you connect your chatbot to custom Lambda functions for doing specific tasks during a conversation

They're used to handle more complex actions that the basic chatbot setup can't do on its own, like checking data from a database or making decisions based on past conversations

Essentially, code hooks make your chatbot smarter and more useful by allowing it to perform these extra steps seamlessly during chats.

  • Choose Update options.
  • Choose Save intent.
  • Choose Build - time for another stretch!
  • Choose Test.
  • Ask for the balance of any of your accounts - your bot should now be able to return (random) bank balance figures!

Woooo set up DONE! πŸ’ͺ

Now let's level up this chatbot:

  • πŸ“¬ Save information about a user in an output context tag.
  • πŸ†™ Create a new intent called FollowupCheckBalance.
  • 🚁 Carry information about the user from CheckBalance to FollowupCheckBalance.

Remember information stored in CheckBalance

Now that BankerBot can check a user's bank account balance, our next level up is to teach it to remember the juicy information it's collected.

After all, it can get pretty frustrating if the a chatbot keeps asking a user for their birthday, especially if it's within the same chat session too.

In this step, get ready to:

  • Save the user's birthday from the CheckBalance intent.
  • In your CheckBalance intent page, scroll down to the Contexts panel.
  • Under the Output contexts drop-down, choose New context tag.

What are context tags?

Context tags in Amazon Lex are used to store and check for specific information across different parts of a conversation. They help save the user from having to repeat certain information

There are two types of context tags in Amazon Lex:

  1. Output context tag: This tells the chatbot to remember certain details after an intent is finished, so other parts of the conversation can use this stored information later. For example, the account type from BalanceCheck could be saved and reused
  2. Input context tag: This checks if specific details are already available before an intent activates. For example, FollowupCheckBalance will check if this conversation already has the user's date of birth saved somewhere, so it won't need to ask for that information again.
  • Name your new context contextCheckBalance
  • Set up the timeout for 5 turns, or 90 seconds. We will keep this short so your chatbot doesn't remember a user's birthday for too long (which might become a security risk).
  • Choose Add.
  • Choose Save intent.
  • Choose Build - time for a few quick questions.
  • Choose Test.
  • Check that the bot still operates the same as usual - i.e., no errors have popped from creating the context tag.

Create the FollowupCheckBalance intent

Imagine that BankerBot just used CheckBalance to give someone their account balance. Now the user has a follow up question - "What about my other account's balance?".

BankerBot would already know the user's birthday information, butttt CheckBalance isn't designed to answer follow up questions like "What about xyz". Adding this to CheckBalance's utterance list will end up confusing BankerBot!

To solve this problem, let's set up a new intent that will handle follow up questions without asking for the user's birthday again 😎

In this step, get ready to:

  • Set up a new intent.
  • From your left hand navigation panel, head back to the Intents page.
  • Choose Add intent.
  • Choose Add empty intent.
  • Under the Intent details pane, use the following properties to set up your next intent:
    • Name: FollowupCheckBalance
    • Description: Intent to allow a follow-up balance check request without authentication.
  • Under the Contexts pane, select contextCheckBalance from the Input context:
  • Under the Sample utterances, enter the following:
How about my {accountType} account?
What about {accountType} ?
And in {accountType} ?
  • Add a new slot:
    • Name: accountType
    • Prompt: For which account would you like your balance?
    • Slot type: accountType
  • Add another new slot:
    • Name: dateOfBirth
    • Prompt: For verification purposes, what is your date of birth?
    • Slot type: AMAZON.Date
  • Choose Save intent.

Finishing Touches for FollowupCheckBalance

We've set up the structure for the FollowupCheckBalance intent - nice work.

But... do you sense anything missing? 🧐

FollowupCheckBalance has an input context tag, but we haven't actually carried over the user's date of birth from CheckBalance yet.

In this step, get ready to:

  • Set up FollowupCheckBalance's dateOfBirth slot to use saved information.
  • Still in your FollowupCheckBalance intent page, expand the dateOfBirth slot.
  • Choose Advanced options.
  • Scroll all the way down to the Default values panel.
  • This panel lets us create default values for the intent's slots.
  • Enter #contextCheckBalance.dateOfBirth

What does #contextCheckBalance.dateOfBirth mean?

This tells Amazon Lex that the input context contextCheckBalance should have the value of dateOfBirth in CheckBalance.

  • Choose Add default value.
  • Choose Update slot.
  • Head to the Fulfillment pane to make sure the Lambda function is also connected to this intent (so random balances are still being returned to the user).
  • Expand On successful fulfillment.
  • Choose Advanced options.
  • Head to the Fulfillment Lambda code hook panel.
  • Select the checkbox to enable a fulfillment Lambda for this intent.
  • Choose Update options.
  • Choose Save intent.
  • Choose Build - you know the drill!
  • Choose Test.
  • In your first test, try to trigger the new FollowupCheckBalance intent you've just created without triggering CheckBalance first.
    • e.g. ask your chatbot What about checking?

Why isn't the intent working?

No matter which utterance you use, you will just get an error response. This is because the FollowupCheckBalance intent's input context isn't available yet. The intent doesn't know your birthday!

  • For your second test, ask for a balance in your account - activate the CheckBalance intent first.
  • Then, the context for date of birth will be carried over to the FollowupCheckBalance intent.
  • Wooo!! Your bot now uses the context from your first check balance request, and doesn't ask for your birthday again for your second request.

Secret mission

Welcome to your 🀫 exclusive 🀫 secret mission!

Your secret mission, should you choose to accept it, is to investigate context expiry and how it can change your users' experience πŸ•΅οΈβ€β™‚οΈ

πŸ’Ž In this secret mission, get ready to:

  • Test BankerBot's memory.
  • Make BankerBot forget user info even faster.
  • Showcase your secret mission in your project documentation.

Context Expiry

Delete Your Resources

Delete Your Resources

Make sure you delete all your resources to avoid getting charged. This is a super important task for every single project you set up. Don't keep your resources in your account if you'll wait to come back to this series on another day.

If you're doing Part Five of this chatbot series today

Did you know Part Five is going to pick up right where you left off in this project?

So you can totally keep your resources if you're also doing Part Five today. Once you're done checking out your documentation for this project, you can head straight to Part Five/

Just make sure to: 1. Complete all your tasks and 2. Download today's documentation before heading to Part Five. Delete the resources in your AWS account if you're planning to continue this series another day.

Before diving into the steps for deleting your resources, why not challenge yourself to delete everything in this project on your own?

Keeping track of your resources, and deleting them at the end, is absolutely a skill that will help you reduce waste in your account.

Do you think you can delete the resources you've created today?

  • Lex Bot (your BankerBot).
  • Delete your Lambda function.
  • Delete your Lambda function's log files.

Yep, all done.

Fantastic! It's the home stretch!

I know, but also, I don't...

If you're feeling stuck (we've all been there!), here's a little guide:

Delete your BankerBot

  • Head to your Amazon Lex console.
  • Choose Bots on the left-hand sidebar.
  • Choose the circle radio button next to BankerBot.
  • Choose Delete from your Action drop-down.
  • Choose Delete.

Delete your Lambda function log files

What are Lambda function log files?

These log files are records of events that happen when AWS Lambda functions are running. These logs include details like errors, warnings, and informational messages that help developers understand how their functions are performing.

In this project, log files have been produced each time your Lambda function was triggered i.e., when CheckBalance gives you a bank balance number.

The logs are stored in CloudWatch, an AWS service used for monitoring and managing all the log data across all your services.

  • Head to CloudWatch in your AWS console.
  • Choose Logs on the left-hand sidebar.
  • Choose Log groups.
  • Select the checkbox next to BankingBot.
  • Choose Delete log group(s) in the Actions menu.
  • Choose Delete.

Nice Work!

Nice Work!

WOOOOOOOO that's another AWS project done βœ… and in the bag!

And there's more to come. In the next project, your chatbot will ⬆️ level up ⬆️ one last time with an intent that can help users transfer money between accounts πŸ‘€

πŸ‘‰ Start project five of this chatbot series now!

To wrap things up, today you've learnt how to:

  • πŸ“¬ Save user information in an output context tag: You stored the user's birthday, which will later save the user from having to repeat themselves. Nice work!
  • πŸ†™ Set up a FollowupCheckBalance intent: You created a new intent named FollowupCheckBalance. This intent is designed to handle the user's subsequent queries about account balances without asking for their birthday again.
  • 🚁 Enable context carryover to FollowupCheckBalance: You enabled context carryover, letting your bot re-use the user's birthday information from the CheckBalance intent in the FollowupCheckBalance intent.

Phew that's a pretty decent list, you've outdone yourself you champ!

Thanks for joining us in today's project, and we'll see you in the next part. 🀝

p.s. Does it say "Still tasks to complete!" at the bottom of the screen?

This means you still have screenshots left to upload, or questions left to answer!

  1. Press Ctrl+F (Windows) or Command+F (Mac) on your keyboard.
  2. Search for the text Return to later.
  3. Jump straight to your incomplete tasks!
  4. πŸ™‹β€β™€οΈ Still stuck? Ask the community!