How do I integrate AWS Lex chatbot to my website?

11,507

Solution 1

To integrate lex bot to website, you need to know about AWS Lex runtime API, AWS IAM and Cognito configuration. This is the most secure way to integrate bot to website.

Here are the steps to add lex bot to your website:

1. Create new identity pool

From the Amazon Cognito console, you choose Manage new identity pool, and then choose Create new identity pool. You provide a pool name (testPoolName), choose Enable access to unauthenticated identities, and then choose Create Pool. Note down the identity pool id.

2. Give lex bot access permission to the identity pool

Go to IAM service. Select Roles. Look for Cognito_testPoolNameUnauth_Role. Click on Attach Policy. Search for AmazonLexRunBotsOnly and attach it.

3. Lex runtime call from website: Here is the sample code for the website

Fill in the identity pool id in the following code. To understand this code, you need to understand AWS Lex run time api.

    <!DOCTYPE html>
<html>

<head>
    <title>Amazon Lex for JavaScript - Sample Application (BookTrip)</title>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.41.0.min.js"></script>
    <style language="text/css">
        input#wisdom {
            padding: 4px;
            font-size: 1em;
            width: 400px
        }
    input::placeholder {
        color: #ccc;
        font-style: italic;
    }

    p.userRequest {
        margin: 4px;
        padding: 4px 10px 4px 10px;
        border-radius: 4px;
        min-width: 50%;
        max-width: 85%;
        float: left;
        background-color: #7d7;
    }

    p.lexResponse {
        margin: 4px;
        padding: 4px 10px 4px 10px;
        border-radius: 4px;
        text-align: right;
        min-width: 50%;
        max-width: 85%;
        float: right;
        background-color: #bbf;
        font-style: italic;
    }

    p.lexError {
        margin: 4px;
        padding: 4px 10px 4px 10px;
        border-radius: 4px;
        text-align: right;
        min-width: 50%;
        max-width: 85%;
        float: right;
        background-color: #f77;
    }
</style>

<body>
    <h1 style="text-align:  left">Amazon Lex - BookTrip</h1>
    <p style="width: 400px">
        This little chatbot shows how easy it is to incorporate
        <a href="https://aws.amazon.com/lex/" title="Amazon Lex (product)" target="_new">Amazon Lex</a> into your web pages.  Try it out.
    </p>
    <div id="conversation" style="width: 400px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll"></div>
    <form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
        <input type="text" id="wisdom" size="80" value="" placeholder="I need a hotel room">
    </form>
    <script type="text/javascript">
        // set the focus to the input box
    document.getElementById("wisdom").focus();

    // Initialize the Amazon Cognito credentials provider
    AWS.config.region = 'us-east-1'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    // Provide your Pool Id here
        IdentityPoolId: 'us-east-1:XXXXX',
    });

    var lexruntime = new AWS.LexRuntime();
    var lexUserId = 'chatbot-demo' + Date.now();
    var sessionAttributes = {};

    function pushChat() {

        // if there is text to be sent...
        var wisdomText = document.getElementById('wisdom');
        if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {

            // disable input to show we're sending it
            var wisdom = wisdomText.value.trim();
            wisdomText.value = '...';
            wisdomText.locked = true;

            // send it to the Lex runtime
            var params = {
                botAlias: '$LATEST',
                botName: 'BookTrip',
                inputText: wisdom,
                userId: lexUserId,
                sessionAttributes: sessionAttributes
            };
            showRequest(wisdom);
            lexruntime.postText(params, function(err, data) {
                if (err) {
                    console.log(err, err.stack);
                    showError('Error:  ' + err.message + ' (see console for details)')
                }
                if (data) {
                    // capture the sessionAttributes for the next cycle
                    sessionAttributes = data.sessionAttributes;
                    // show response and/or error/dialog status
                    showResponse(data);
                }
                // re-enable input
                wisdomText.value = '';
                wisdomText.locked = false;
            });
        }
        // we always cancel form submission
        return false;
    }

    function showRequest(daText) {

        var conversationDiv = document.getElementById('conversation');
        var requestPara = document.createElement("P");
        requestPara.className = 'userRequest';
        requestPara.appendChild(document.createTextNode(daText));
        conversationDiv.appendChild(requestPara);
        conversationDiv.scrollTop = conversationDiv.scrollHeight;
    }

    function showError(daText) {

        var conversationDiv = document.getElementById('conversation');
        var errorPara = document.createElement("P");
        errorPara.className = 'lexError';
        errorPara.appendChild(document.createTextNode(daText));
        conversationDiv.appendChild(errorPara);
        conversationDiv.scrollTop = conversationDiv.scrollHeight;
    }

    function showResponse(lexResponse) {

        var conversationDiv = document.getElementById('conversation');
        var responsePara = document.createElement("P");
        responsePara.className = 'lexResponse';
        if (lexResponse.message) {
            responsePara.appendChild(document.createTextNode(lexResponse.message));
            responsePara.appendChild(document.createElement('br'));
        }
        if (lexResponse.dialogState === 'ReadyForFulfillment') {
            responsePara.appendChild(document.createTextNode(
                'Ready for fulfillment'));
            // TODO:  show slot values
        } else {
            responsePara.appendChild(document.createTextNode(
                '(' + lexResponse.dialogState + ')'));
        }
        conversationDiv.appendChild(responsePara);
        conversationDiv.scrollTop = conversationDiv.scrollHeight;
    }
</script>

Solution 2

Here is the detailed blog on this topic. Below is the summary if you are looking for a short answer.

There are two steps involved in order to deploy a chatbot which can interact with your website users.

  1. Create and publish a chatbot:

The first step is Creating a chatbot. Lex provides a simple UI where you can configure what a user says and the corresponding reply from the bot. It is not necessary to learn and AWS lambda to create a simple FAQ-like bot. The Lex UI is sufficient for this. If you are creating a more powerful bot which can identify the actionable detail and perform some business logic on user's query you need to use AWS lambda function as the fulfillment.

For example, if you are creating a hotel booking bot and user says :

Book me a hotel for tomorrow in London

The Lex will give you the booking information as below if you have configured the slots.

{
"bookingDate": "06-07-2019" //equivalent date of tomorrow
"location":"london"
}

Lex will send this information to your lambda function if you have enabled AWS lambda as fulfillment. Then your lambda function has to call the hotel booking API and send confirmation to the user.

Once this setup is ready you can publish your bot and move to the next step integrating it to your website.

  1. Integrate the bot into your website

Here you have two options:

  • AWS SDK provides APIs to integrate a chatbot into the website. You can check this answer for more detail on AWS APIs.
  • Another convenient way is to use any service like Kommunicate which provide a codeless integration with Lex platform. Kommunicate is a Bot+human hybrid customer support platform which provides functionality like bot to human handoff, Actionable messages, routing rules etc. You can follow these steps to integrate a Lex bot into website using Kommunicate:

    1. Sign up to the kommunicate, go to bot section and choose Amazon lex.
    2. Fill up the required detail and click on "let This bot handle all conversations."
    3. Get the installation script from install section and paste it in your website.
    4. Your bot is ready to reply your users.

Solution 3

Played around with AWS Lex a bit recently, and it seems that you cannot really avoid using Lambda code.

First the validation and fulfilment code hooks will be lambda functions and for any half-decent lex bot conversation you will need those.

Second is the chat client: if you do not want to use the existing list of native chatbot integrations (currently Facebok, Twilio SMS and Slack) you will need a custom implementation. A direct PHP curl might be an option (accessing the API directly), but I'd highly recommend using a standard AWS API Gateway / AWS lambda setup to create a lex client and use the convenience of SDKs instead. It's a very flexible setup, super easy. We have picked in up in days, with minimal python code base using boto3 SDK, with virtually no experience in python at all.

Hope it helps!

Share:
11,507
Winfred Peng
Author by

Winfred Peng

Updated on June 03, 2022

Comments

  • Winfred Peng
    Winfred Peng about 2 years

    My website is doing customer service & support ticket system.

    But the way of integrating AWS lex seems not as easy as FB is.

    The thing I wanna do is letting Lex Bot reply tickets for the customer on my website.


    Do I need to learn AWS Lambda and API Gateway first for integrating Lex?

    I want to know how to call the lex bot API in PHP curl.

    As API Docs said.

    But I am not sure why the POST url is like a relative path.

    Anyway, thanks for the help.

  • SMPLYJR
    SMPLYJR about 5 years
    Hi @Jaya, this was giving me a CORS issue. Do you know where to configure it?