36,59 €
Build artificial intelligence (AI) powered voice and text conversational interfaces with Amazon
Key Features
Book Description
Have you ever wondered how Alexa apps are made, how voice-enabled technologies work, or how chatbots function? And why tech giants such as Amazon and Google are investing in voice technologies? A better question is: why should I start developing on these platforms? Hands-On Chatbot Development with Alexa Skills and Amazon Lex covers all features of the Alexa Skills kit with real-world examples that help you develop skills to integrate Echo and chatbots into Facebook, Slack, and Twilio with the Amazon Lex platform.
The book starts with teaching you how to set up your local environment and AWS CLI so that you can automate the process of uploading AWS Lambda from your local machine. You will then learn to develop Alexa Skills and Lex chatbots using Lambda functions to control functionality. Once you've come to grips with this, you will learn to create increasingly complex chatbots, integrate Amazon S3, and change the way Alexa talks to the user. In the concluding chapters, we shift our focus to Amazon Lex and messaging chatbots. We will explore Alexa, learn about DynamoDB databases, and add cards to user conversations.
By the end of this book, you will have explored a full set of technologies that will enable you to create your own voice and messaging chatbots using Amazon.
What you will learn
Who this book is for
Hands-On Chatbot Development with Alexa Skills and Amazon Lex is for developers who are interested in building conversational bots and Alexa skills with Amazon. Prior experience with JavaScript programming is required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 282
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudhariAcquisition Editor:Divya PoojariContent Development Editor:Chris D'cruzTechnical Editor: Sneha HanchateCopy Editor:SAFISProject Coordinator: Namrata SwettaProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics:Jisha ChirayilProduction Coordinator:Shraddha Falebhai
First published: October 2016
Production reference: 1270918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78899-348-7
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Sam Williams qualified with an aerospace engineering master's degree, then became a self-taught software developer while holding down his first job. While traveling, he started to write articles about the tech he was learning about and accrued an audience of readers on Medium and freeCodeCamp.
Currently, Sam works as a lead chatbot developer for the SmartAgent team at MissionLabs, building custom systems for large retailers. His role ensures that he is working with the newest chatbot technologies and is constantly pushing their capabilities.
Walter Quesada is a software engineer and technologist with over 20 years' experience architecting and developing solutions for companies of all sizes. He currently serves as the conversational systems lead at the PwC Applied Research Lab, where he focuses on creating a more conversational future with voice and chatbots. He is also an Amazon Alexa Champion, an O’Reilly author with a book titled Programming Voice Interfaces, as well as being a Pluralsight instructor with two courses, Developing Alexa Skills for Amazon Echo and Creating Voice and Chatbots that Work Everywhere.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Chatbot Development with Alexa Skills and Amazon Lex
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Understanding Chatbots
What are chatbots?
What makes up a chatbot?
Intents
Slots
Utterances
Designing conversation flows
Starting with the perfect conversation diagram
Conversation flow diagrams
Creating a conversation flow diagram
User stories
Best practices
Handling errors
Missed utterances
External APIs
Errors in your code
Tone of voice
Identifying suitable use cases
Designing the information for the delivery method
Amazon Alexa and Lex
Amazon Alexa
Amazon Lex
Summary
Questions
Getting Started with AWS and Amazon CLI
Technical requirements
Creating an account
Setting your region
Navigating around AWS
Creating a Lambda
AWS Console
Setting up the Lambda
Writing your Lambda function's code
Triggering Lambdas
Methods for working with Lambdas
Method 1 – Lambda Console
Method 2 – Cloud9 editor
Method 3 – Local editing
Creating the best local development environment
Choosing an IDE
Installing Node and NPM
Folder structure
Setting up AWS CLI
Creating a Lambda using AWS CLI
AWS CLI build script
Git
Local development setup
Summary
Questions
Creating Your First Alexa Skill
Technical requirements
Alexa Skills Kit
Creating a Lambda to handle the request
Creating handlers
Building and configuring the Lambda
Finishing skill configuration
Testing your skills
Troubleshooting your skill
Creating a more useful skill
Conversational flow diagram
Creating the Alexa Skill
Creating an Intent
Internal Slots
Finding the Skill ID
Creating the Lambda
Handling the whichCar Intent
Amazon S3
Accessing our S3 data
Adding S3 permissions
Dealing with our data
Testing our Lambda
Finishing the Alexa Skills Kit Configuration
Testing
Launching your skill
Summary
Questions
Further reading
Connecting Your Alexa Skills to External APIs
Technical requirements
External APIs
Open Weather Map API
Creating our weather skill
Conversation flow design
Creating the skill on Alexa Skills Kit
Building Lambda to handle the requests
Making an API request
Final setup and testing
Improving user experience
Error-handling our API calls
Session memory
SSML
Testing
Summary
Questions
Further reading
Building Your First Amazon Lex Chatbot
Technical requirements
Creating an Amazon Lex chatbot
Setting up the chatbot
Creating an Intent
Testing your chatbot
Publishing your bot
Using Slots
Creating an FAQ chatbot
Setting up Lex
Gathering the data
Creating the Intents
Creating the Lambda Handler
Creating a response
Lambda fulfillment
Building and testing
Lex responses
elicitSlot
elicitIntent
confirmIntent
close
delegate
Summary
Questions
Connecting a Lex Bot to DynamoDB
Technical requirements
Designing the flows
Perfect conversations
Flow diagrams
Building the chatbot
Product find
Creating the Lambda
Creating the data
Lambda testing
Completing the intent
Add to cart
Creating the Lambda
DynamoDB
Adding Dynamo permissions
Testing
Checkout
Creating the Lambda
Testing
Saving our cart
Creating the Lambda
Dynamo changes
Testing
Retrieving a saved cart
Creating the Lambda
Testing
What's in my cart?
Creating the Lambda
Testing
Testing the whole bot
Summary
Questions
Further reading
Publishing Your Chatbot to Facebook, Slack, Twilio, and HTTP
Technical requirements
Integrations
Facebook Messenger
Creating and connecting a Facebook Messenger app
Slack
Creating and connecting a Slack app
Twilio
Creating and connecting Twilio
HTTP endpoint
Creating the Lambda
Testing
Connecting API Gateway
Testing
Building the API
Web user interface
HTML
Creating our script
Styling the frontend
Summary
Questions
Improving the User Experience for Your Bots
Technical requirements
Response cards in Amazon Lex
Creating a card
Using cards in chats
Alexa search queries
Google Cloud Platform
Continuing Lambda building
Rebuilding the skill and testing
Lex utterance monitoring
Summary
Questions
Review and Continued Development
What we've learned
Conversation design
Amazon Web Services
Amazon Alexa
Amazon S3
Using APIs
Amazon Lex
Dynamo DB
Publishing Lex chatbots
Advanced features
Continuing your learning
Alexa
Amazon Echo Spot and Amazon Echo Show
Building a library of functions
Lex
Alexa and Lex
Improving the build process
Integrating more AWS services
Integrating other APIs
The future of chatbots
Language understanding
Working with spoken interactions
Improved device interaction
Connected devices
Unique voice-based systems
General Artificial Intelligence
Improving people's opinions
Summary
Appendix A
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Appendix B
Debugging
Debugging Alexa Skills
Check the utterances
Save and build your model
Check your Endpoint
Added Alexa as a trigger for your Lambda
Debugging Lex chatbots
Check your utterances
Check the intent response
Save intents, build, and deploy
Check your connected platform
Check your Lambdas are working
Debugging Lambdas
Install all of the required packages
Check your permissions
Correct your Lambda code
Check external services
Other Books You May Enjoy
Leave a review – let other readers know what you think
Chatbots are becoming more and more common in everyday life, with Alexa currently being in 16% of households and over 100,000 Facebook chatbots. Chatbots provide a way to interact with technology that is a lot more natural for people, through conversation.
In this book, we'll learn how to build our own voice and text-based chatbots using Amazon Alexa and Lex. These platforms allow us to use very powerful technology to understand what the users are saying. We also learn about the design process when creating a chatbot and how we can provide a great experience for our users.
This book is for anyone who wants to be able to build Alexa Skills or Lex chatbots. Whether you want to build them for personal projects or as part of your job, this book will give you all the tools you need. You'll be able to take an idea, build the conversation flow diagrams, test them with user stories, and then build your Alexa Skill or Lex chatbot.
Chapter 1, Understanding Chatbots, starts by explaining the concepts involved in building a conversational interface. We will learn how to start with an example user conversation and build flow diagrams to visualize the path that the user takes with the chatbot. The chapter will then discuss the types of chatbots and will introduce us to voice skills for Amazon Alexa and text-based chatbots for Amazon Lex.
Chapter 2, Getting Started with AWS and Amazon CLI, teaches us about AWS Lambdas and how these serverless functions can be built and tested in the browser. After building our first Lambda, we discuss three different ways to build and deploy them, comparing the merits and limits of each. To create the most powerful development environment possible, we use aws-cli to build a script that allows us to deploy Lambdas from our local development environment.
Chapter 3, Creating Your First Alexa Skill, introduces us to the Alexa Skills Kit and has us build our first Alexa Skill. We learn about how to build a Lambda to handle our users' requests and return the response that we want to send to the user. To create a more realistic situation, we create a skill that suggests a car for the user, based on a series of questions. We use the flow design process discussed in Chapter 1, Understanding Chatbots, to map out our users' interactions with our skill before creating the intents. The Lambdas that we use also increase in complexity with slot eliciting and with the inclusion of data that is stored in S3.
Chapter 4, Connecting Your Alexa Skills to External APIs, takes our Alexa skills to a new level of functionality by accessing external APIs. API access can provide massive amounts of functionality to your chatbots, but it needs to be done correctly. We'll learn about two of the best ways to handle errors and use them to build a weather skill.
Chapter 5, Building Your First Amazon Lex Chatbot, moves the focus onto Amazon Lex chatbots. The concepts and components are similar to those we used to build our Alexa skills, so we only need a quick refresher before building our first Lex chatbot. While Lex and Alexa are similar, we quickly see how there are some key differences in the way that the intents are handled. To create a more realistic project, we build an FAQ chatbot. This Lex chatbot takes advantage of the intent handling by triggering one of three Lambdas, based on the intent that was hit. These Lambdas access the responses from S3 and reply using a LexResponses class, which we will build.
Chapter 6, Connecting a Lex Bot to DynamoDB, introduces us to DynamoDB databases and how we can use them to store information about the users' interactions. We use this to build ourselves a shopping chatbot that stores a user's cart, even allowing them to save their cart for later. The complexity of the flows for this chatbot is a lot closer to what you would expect from a real project, and that is reflected in the amount of code.
Chapter 7, Publishing Your Chatbot to Facebook, Slack, Twilio, and HTTP, teaches us how we can publish our chatbots and integrate them into platforms, including Facebook and Slack. We use Amazon Lex's built-in integration tools to make this process as easy as possible. Next, we build an API endpoint, using API Gateway and Lambdas, so that we can develop integrations for other services. We use this API ourselves to create our own front-end interface, which we could integrate into other websites.
Chapter 8, Improving User Experience for Your Bots, discusses a few ways to make the experiences of your users more enjoyable. This covers creating and sending cards in Lex conversations and using search query slot types in Alexa skills. Cards provide the user with a much more visual interaction, while search query slots allow a user to search for a much wider range of values that we could allow with a custom or built-in slot type.
Chapter 9, Review and Continued Development, gives us a few pointers on the directions we can go to continue developing our chatbot skills. There are separate pieces of advice for people who prefer Alexa, and those who want to pursue more Lex skills, as well as a set of skills that will improve your abilities with both chatbot platforms. After this, we discuss the future of chatbots, where they are going, and what needs to happen before they become truly integrated into our daily lives.
Here is a list of things that you should have to make the most out of this book. You can complete this book without the second or third items, but lacking them will make the process harder:
Knowledge of at least one high-level programming language supported by AWS, but ideally JavaScript
Basic experience using command-line tools for Linux or macOS
A basic understanding of AWS services is helpful, but not required
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Chatbot-Development-with-Alexa-Skills-and-Amazon-Lex. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788993487_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
html, body, #map { height: 100%; margin: 0; padding: 0}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialogue boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
To create successful chatbots using Alexa or Lex, you first need to understand the components that make up a chatbot. These parts can then be used to create conversation diagrams and flow diagrams, helping visualize the user's path through the conversation. Being able to have this map for the user's conversation makes building chatbots far easier and quicker.
Toward the end of the chapter, we will also introduce Alexa and Lex and have a look at their similarities and differences. We'll also have a quick look at some of the use cases for each of them.
The chapter will explain the following topics:
Introducing chatbots
Designing conversation flow diagrams
Best practices
Amazon Alexa and Amazon Lex
Chatbots are a new way to interact with a user in a more human way, through conversation. This is vastly different from existing methods, which provide minimal interaction or personalization.
Chatbots can be either voice or text-based interactions, allowing them to be integrated into existing websites and apps or used in phone calls and virtual assistants.
They have recently been put in the spotlight with products such as Amazon Echo and Google Home, as well as an enormous number of Facebook Messenger chatbots. These advances in technology allow you to check the weather or order a pizza without looking at a screen, or get personalized information without having to wait to talk to a call center.
A chatbot is very different in the way that it interacts with a user, and therefore how it works is also very different. There are three main components of a chatbot: intents, slots, and utterances.
Intents are the most important part of a chatbot. They are the tasks or conversations that the chatbot can process. They are called intents because they are the things that the user intends to do.
Intents can vary in complexity from very simple to extremely complicated. A basic intent may just beSayHello, which just says "Hi" to the user. A more complex intent may be booking a holiday, choosing and buying a pair of shoes, or ordering a pizza. They can be designed to be as elaborate as your imagination allows.
They are started or triggered when the user says one of thesample utterances. The sample utterances are a list of words or phrases that the user might say when they are trying to start an intent. Each intent can have lots of sample utterances. In theSayHelloexample, they might be "Hello chatbot", "Hey there chatbot", or just "Hi".
To allow the chatbot to be really useful, it has to be able to gather details about what the user is asking for. If you are wanting to order a pizza, the chatbot needs to know what toppings you want, what style of base you want, and where you want it delivered to. This information is collected and stored inslots.
Slots are designed to only accept certain types of information. If you were trying to find out whether they wanted a large, medium, or small pizza, it wouldn't be very useful if they could enter any random information. Defining the information that can be stored in a certain slot is called creating aslot type.
To make use of the information gathered in the slots, they can be accessed in the next stage of the chatbot logic. This could be as simple as saying "You have ordered alargeHawaiianpizza", where the size and topping are exactly what the user previously ordered.
An utterance is a word or phrase that has been said. This is key to chatbots as this is how a user interacts with the chatbot.
These utterances can trigger which intent the user is trying to access and they can also be used to get the exact information needed to fill the slots.
Now that we understand the components that make up a chatbot, we can start to design the conversations that we want our chatbot to handle. Designing conversations now makes it a lot easier to visualize how the chatbot will work, making it easier and quicker to build. Designing conversations in this way makes them easy to understand, making it a great tool for creating chatbots with people who can't code.
This design method will work for voice or text chatbots; just imagine the textboxes as speech bubbles.
Everything has to start somewhere, so it may as well be perfect. The aim of this stage is to have a basic conversation diagram that we will later expand into a detailed flow diagram.
To do this, you need to think about what the perfect conversation with your user would be. Start by writing down what the user will say and how the bot will respond. This is an example of ordering a pizza:
This can be done in lots of ways: with flow diagram software, using two phones or two messaging accounts, or simply with pen and paper. The aim is just to understand how the chatbot is going to be interacting with the user and what utterances the user is likely to say.
Now that you have a basic conversation diagram, we need to make it into a flow diagram. A flow diagram is different from a conversation diagram in a few key ways:
Each part of a flow diagram has its own symbol, making it easy to understand what is happening at each stage.
A flow diagram contain more than just the conversation. It also describes the logic, information, and processes that take place behind the scenes.
Flow diagrams aren't linear. This means that they can describe lots of conversations where the user says different things.
To properly describe our chatbots, we need to have a symbol for each of the parts of the conversation. To start with, we are going to be using six, but we can add more symbols later on:
To create our flow diagrams, we'll be using flow diagram software. There are a couple of reasons we want to use flow diagram software instead of a normal document or even creating them by hand:
They are easily editable. We are going to be changing the stages of the conversational flow and the text of utterances and replies as we work through this book. Having to redraw the diagram every time you make a change would be very time-consuming.
It's the easiest way to make flow diagrams. The symbols snap into place and are easy to edit and modify. Doing flow diagrams in Word would be far more time-consuming.
In all of the examples throughout this book, we'll be using www.draw.io, but if you have a different flow diagram software that you prefer then that will work too. We use draw.io as it's free, online, and is very easy to use.
User stories are a vital tool in the design and testing of chatbots. They are stories about fictional users, what they want, and how they will interact with your bot. When we create a user story, it needs to be as close to a real user as possible. They should be based on a real user or the type of user that would be using your chatbot. If you have existing customers that you are wanting to target your chatbot toward then you can create data-driven user stories.
To create a user story, start by describing the user and why they are talking with your bot. Examples of the pizza ordering bot might be the following:
Chris, a 23-year-old joiner. Wants to order a pizza on his phone so he can pick it up on the way home from work.
Claire, a 35-year-old bank manager. Ordering a pizza using Alexa while she watches TV.
The user descriptions don't have to be very long or complicated, but they have to represent the kind of users the bot will get.
For each user, go through the flow diagram pretending that the bot is talking to that user. The aim of this is to test your flow diagram before we start building the bot. If you find that the conversation doesn't work for a certain part of the flow diagram, changing it now will save you time later on.
For simple examples like this pizza order, there won't be a big difference between all of the conversations, but user stories will become more important as we create more complicated flow diagrams.
Anyone can make a chatbot. With a bit of practice, you can build a simple bot in a few hours. The problem with building bots like this is that, as they grow in scope and complexity, they can very easily become unmanageable. Simple changes can result in hours or even days of bug fixing and it can ruin the joy you get when you finally get the chatbot working.
To avoid the horror of working with a disorganized and complex chatbot, there are a few best practices. Following these will reduce your headache later on and allow you to quickly and easily add new features.
Throughout a user's conversation with a chatbot, there are a lot of points where errors can occur. Errors can occur when an utterance isn't understood, an API returns an error or when there is a mistake in the developer's code. Each of these needs to be caught and dealt with properly. We'll cover how to use try/catch and the to() method to catch these errors inChapter 4, Connecting Your Alexa Skill to External APIs.
The most common error will be when utterances aren't understood or aren't what the chatbot expected. This can be because the user typed something incorrectly, misspelled a word, or just typed a response you hadn't thought of. Alexa and Lex both use natural language understanding (NLU) to try to reduce the errors from misspelling and varied responses but they aren't perfect.
Because not understanding the user's utterance is such a common error, both Lex and Alexa also have systems to handle them. This involves a failure phrase that can be sent to the user when the chatbot doesn't understand what the user just said. Make sure that this is set up properly and that you are asking the user to try again or to choose a different option:
Alexa and Lex also have a feature that stores all of the times that it couldn't understand an utterance. Using this list, you can add more sample utterances to help the chatbot understand more. Doing this regularly can give a massive boost to your user satisfaction, as well as helping you understand how your users interact with your bot.
