Tutorial: Build an AI Assistant with API.ai and Amazon Lambda
Tech giants are betting big on conversational interfaces; Facebook acquired wit.ai, Google acquired api.ai, and Amazon announced Lex. These services all make it easy to parse user intention from natural language. In this tutorial, we’ll demonstrate how to connect a conversational interface with a third-party API. These steps will enable you to build rich experiences for the Google Home, Amazon Echo, Microsoft Cortana, Facebook chatbots, Slack Bots, or another AI assistant. For this example, we’ll build a Google Home action that tells us the height of Star Wars characters. We’ll use api.ai, Amazon Lambda and API Gateway, and the Star Wars API.
1. Create Your Conversational AI Assistant
- Sign up for api.ai. I used my Google Account.
- Click on “Create Agent.”
- Give your agent a name and description.
Name: StarWars
Description: A conversational assistant that can tell you the height of various star wars characters. - Click “Save.”
2. Create A User Intent
An intent describes something a user is asking for. For example, a customer service agent may have a “returns” intent and a “tech support” intent. Our intent is for when the user asks about the height of a star wars character.
- Add a new intent by clicking the “+” next to “Intents.”
- Populate the intent.
- Intent Name: Height Intent
- Under User Says, we add different ways to express the intention that the user wants to know the height of a Star wars character:
- “How tall is Luke Skywalker?”
- “How short is Yoda?”
- “What is the height of Boba Fett?”
- “Tell me how big Chewbacca is.”
- Tag parameters. Notice that api.ai is automatically recognizing “Luke” and “Yoda” as a
given-name
and “Skywalker” as alast-name
. Click on “Boba” and “Chewbacca” and identify them asgiven-name
. Assign “Fett” aslast-name
.
- Test the intent in the right hand pane.
Type “How tall is Yoda?”
Notice how theHeight Intent
is correctly identified, even though we didn’t train that exact wording. Also notice that “Yoda” has been correctly extracted as agiven-name
. - Click “Save.”
At this point, we’ve successfully trained our agent to:
- Recognize when users ask about a Star Wars character’s height, and
- Extract the character’s name
Now, we’ll create a microservice to accept and process this information.
3. Create an Amazon IAM User
- Sign up for Amazon AWS. I was able to use my existing Amazon account. You will have to enter a credit card (I used the one they had on file). Amazon bills based on usage, but you get 1 million free requests per month; this is more than enough to hobby-develop for free.
- Create an IAM user. AWS Identity and Access Management (IAM) enables you to securely control access to AWS services and resources. We’ll create an IAM user so we aren’t using our root Amazon account.
- Navigate to console.aws.amzon.com/iam
- Select “Users” from the left pane. Click “Add User.”
- Fill in the user info:
User name: TestUser
Access type: AWS Management Console accessConsole Password: Custom Password
Uncheck “Require password reset” - Click “Next: Permissions”
- Click the checkboxes to add the following Permissions:
- Click “Next: Review.” Your overview should look like this:
- Click “Create User”
- Sign in to your new IAM user.
4. Create A Lambda Function
- Navigate to https://console.aws.amazon.com/lambda/home
- Click on “Create a Lambda function.”
- Configure the Lambda function:
- Use the “hello-world” blueprint
- Under “Configure Triggers”, just press “Next.”
- Under “Configure Function”
Name: starWarsBot
Description: A middleman between api.ai and swapi.co
- Create a Handler and Role:
Handler: index.handler
Role: Create new role from templates
Role Name: simpleMicroservice
Template: Simple Microservice permissions - Click “Next.”
5. Code Your Lambda Function
At this point we have a hosted node.js function that we can edit on the web. Now, we’ll change the code to accept our request from api.ai and query swapi.co.
- Replace the Lambda code with the following code:1234567891011121314151617181920212223242526272829303132333435363738394041424344'use strict';let http = require('http');let starWarsAPI = `www.swapi.co`;exports.handler = function(event, context, callback) {let firstName = event.result.parameters['given-name'];let lastName = event.result.parameters['last-name'];let options = searchPeopleRequestOptions(firstName, lastName);makeRequest(options, function( data, error) {let person = data.results[0];if (person) {let height = person.height;let response = person.name + " is " + height + " centimeters tall.";callback(null, {"speech": response});}else {callback(null, {"speech": "I'm not sure!"});}});};function searchPeopleRequestOptions(firstName, lastName) {return {host: starWarsAPI,path: `/api/people/?search=`+firstName+'+'+lastName};}function makeRequest(options, callback) {var request = http.request(options,function(response) {var responseString = '';response.on('data', function(data) {responseString += data;});response.on('end', function() {var responseJSON = JSON.parse(responseString);callback(responseJSON, null);});});request.end();}
given-name
andlast-name
from the inboundevent
and formats a web request towww.swapi.co/api/people/?search
. It then extracts theheight
from the response and returns{"speech":" "}
to api.ai. - Press “Save.”
- Test Your Lambda Function.
- Back at api.ai, run a test query, and press “show JSON.”
- Copy the JSON
- Configure a Test Event for your Lambda
- Click Actions > Configure Test Event.
- Paste the JSON.
- Click “Save and Test.” Your test should succeed and you should see the output:123{"speech": "Chewbacca is 228 centimeters tall."}
6. Create an Endpoint in API Gateway
At this point, we have:
- An api.ai agent that collects user input and POSTs JSON.
- A Lambda function that can consume that JSON, query swapi.co, and return a speech response.
Now, we need to enable the two pieces to communicate with each other.
- Navigate to http://console.aws.amazon.com/apigateway/home
- Create a New API:
API name: Starwars
Description: A microservice for finding information about star wars - Create an API endpoint:
Actions > Create Resource
Resource Name: height
Actions > Create Method > POST
Integration Type: Lambda Function
Lambda Region: **Must match your Lambda region**. (You should be able to figure out the region from the page url.)
Lambda Function: starWarsBot - Deploy your API:
Actions > Deploy API
Deployment Stage: [New Stage]
Stage Name: beta
Click Deploy - Copy the “invoke URL”
7. Use Your New API for Intent Fulfillment
- Back at api.ai, choose “Fulfillment” from the left pane.
- Enable the switch, paste the URL from your API, and complete the url to point at the “/height” endpoint.
- Click “Save.”
- Navigate to our intent (Intents > Height Intent), expand the fulfillment section, and check the “Use webhook” box.
- In the “Try it now” field in the right pane, try another query.
You should see the correct response: “Yoda is 66 centimeters tall.”
8. Test On The Google Home
- Navigate to “Integrations” from the left pane.
- Turn on “Actions on Google.”
Invocation name for testing: Star Wars - Press “Authenticate.” This will have you sign in to your Google Account. You’ll want this to be the same as the Google Account that the Google Home is set up with.
- Press “Preview.” A Message should pop up on the bottom of the screen:
- Click on the link in the pop up. (Or here.)
- Test on the Web Simulator.
Note: You must first ask to talk to the Star Wars agent, or phrase your question with the agent’s name: (“Ask Star Wars how tall Yoda is.”) - Test on the Google Home!
Try out the agent on any Google Home set up with the same Google Account that you developed with. If the package preview runs out, you can refresh it for 24 hours on the Web Simulator by clicking Action Package > Preview for 24 hours.
0 comments:
Post a Comment
Don't Forget to Share and Comment