Connect Amazon Lex with Lambda

Watch the magic happen once you connect Lex with Lambda!

Introduction

⚑️ 30 second Summary

Welcome to Part THREE 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 Parts ONE and TWO, you learnt how to:

  • πŸ’¬ Define intents
  • πŸ”€ Provide variations in your bot's responses
  • 🌟 Set up a custom slot type
  • πŸ§ͺ Build and test your bot using text and speech

Now you're on part THREE πŸ€–πŸ€–πŸ€–

You'll learn how to use Amazon Lambda to return a random bank balance! If you haven't done Project TWO 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: You are here!
  4. Part 4: Save User Info with a Lex Chatbot

Before we start...

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

Set up a new Lex chatbot

In this project, our goal is to get BankerBot to check users' bank account balance and return a random bank balance.

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

In this step, get ready to:

  • Create a new bot from scratch on Amazon Lex.
  • Set up a WelcomeIntent.
  • Customize a FallbackIntent, i.e. your BankerBot says a customised error message if it doesn't understand the user's input.
  • Set up a CheckBalance with a custom slot type called accountType.

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 Part 1 and Part 2 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 and 2.

Once you're finished, you should have:

  • A new Lex chatbot called BankerBot.
  • WelcomeIntent set up.
  • FallbackIntent customised, i.e. your BankerBot says a customised error message if it doesn't understand the user's input.
  • CheckBalance set up with a custom slot type called accountType.

You got this! Challenge yourself to complete this in less than 20 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, i.e. your BankerBot says a customised error message if it doesn't understand the user's input.
  • CheckBalance set up with a custom slot type called accountType.

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 another service called Lambda later in this project!
  • 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! Woooooo welcome.
  • 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!

Woooo set up DONE! πŸ’ͺ

Now let's level up this chatbot:

  • 🧠 Define an AWS Lambda function that will get a user's balance.
  • πŸ”— Connect your AWS Lambda function with your Amazon Lex chatbot.
  • 🀝 Connect your CheckBalance intent with your Lambda function.

Create Your AWS Lambda Function

Now that BankerBot can grab a user's account type and birthday, it's high time that we give the user something back... their bank balance!

Lex doesn't come with the smarts to calculate bank balances on its own, but luckily it doesn't have to.

We'll be using another AWS service, AWS Lambda, to generate a random number on the fly (whenever a user asks for their balance). You can think of Lex as the interface that the user sees and chats with, while Lambda is the calculator that's out of sight but works in the background.

Easy peasy, there's no experience with Lambda required to do this.

In this step, get ready to:

  • Use AWS Lambda to generate random bank balance numbers.
  • Head to Lambda in your AWS Management Console.

What is AWS Lambda?

AWS Lambda is a service that lets you run code in the cloud without needing to manage any computers/servers - Lambda will manage them for you.

Lambda runs your code only when needed and scales automatically, from a few requests per day to thousands per second - all you need to do is supply your code in one of the languages that Lambda supports.

  • Select Create a function.
  • 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

Oooo what's in the code file?

This Python script helps your chatbot give users quick answers about their account balances.

When someone asks about their account balance to your chatbot, Lex will ask your Lambda function to run this code, which will pick a random number to pretend it's the balance.

Lambda will pass this random number to Lex, who will then push the bank balance figure to the user through your chatbot.

  • 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

That was your Lambda function all ready to go!

Lambda is totally prepared now to start generating users' bank account balances, but... it doesn't actually know when to do it, or which intent to do it for yet.

We need Lex and Lambda to join forces so that when a user asks for a bank account balance, Lex can trigger Lambda to calculate a number right away.

In this step, get ready to:

  • Connect your Lambda function to BankerBot.
  • 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.

What is TestBotAlias?

TestBotAlias is a default version of your bot that's made for testing or development.

This is the playground version of your bot that you'll use to make sure everything works smoothly before rolling out changes!

  • On the Languages panel, click 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.

What does $LATEST mean?

Using the $LATEST version means you're directing your alias to always use the most up to date version of this Lambda function. This setup is a time saver that lets you immediately test any changes in your function.

  • Choose Save.

Connect your CheckBalance intent with your Lambda function

Awesome, we're one step closer.

The Lambda function is now connected with BankerBot βœ…, but Lex still doesn't know which intent inside BankerBot will actually use the Lambda function.

Is it the FallbackIntent? Nope.

How about the WelcomeIntent? Not quite.

Time to make a direct connection between CheckBalance and the Lambda function!

In this step, get ready to:

  • Connect your Lambda function to the CheckBalance intent.
  • Navigate to your CheckBalance intent.
  • Scroll down to Fulfilment panel.

What is fulfilment?

In Amazon Lex, fulfilment 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 fulfilment. 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 fulfilment bubble.
  • Choose Advanced options.
  • Under the Fulfilment Lambda code hook panel, check the checkbox next to Use a Lambda function for fulfilment.

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!

Secret mission

Welcome to your 🀫 exclusive 🀫 secret mission!

Your mission, should you choose to accept it, is to customize your Lambda function!

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

  • Edit your Lambda function code.
  • Test BankerBot again to see your customized function in action.
  • Showcase your secret mission in your project documentation.

Customise your Lambda function

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 you're doing Part Four of this chatbot series today

Did you know Part Four 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 Four today. Once you're done checking out your documentation for this project, you can head straight to Part Four!

Just make sure to: 1. Complete all your tasks and 2. Download today's documentation before heading to Part Three. 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

  • Head to your AWS Lambda console.
  • Choose Functions on the left-hand sidebar.
  • Choose the circle radio button next to BankingBotEnglish.
  • 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 ⬆️ again with the ability to remember a user's birthday... and pass that info to another intent πŸ‘€

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

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

  1. πŸ› οΈ Set up a Lambda function: You configured a new Lambda function to enhance your chatbot’s capabilities.
  2. πŸ”„ Integrate the Lambda function with your chatbot's alias: You connected the Lambda function to your chatbot’s alias for seamless interaction.
  3. 🎯 Use code hooks in an intent: You've implemented code hooks to handle the final fulfilment step of the intent, ensuring accurate and efficient responses.

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!