How do I integrate the AWS Lex chatbot into my site?

My site works with a customer support system.

But the way to integrate AWS lex seems to be not as easy as FB.

What I want to do is let Lex Bot manage tickets for a client on my site.


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

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

As the API Docs said .

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

Thanks for the help anyway.

+8


source to share


4 answers


To integrate a lex bot into a website, you need to know about the AWS Lex API, AWS IAM API, and Cognito. This is the safest way to integrate a bot into a website.

Below are the steps to add a lex bot to your site:

1. Create a new pool of identifiers

In the Amazon Cognito console, select Manage New Identity Pool and then select Create New Identity Pool . You provide a pool name (testPoolName), select "Enable access to unauthorized identifiers" and then select "Create pool". Make a note of the ID pool ID.

2. Grant lex bot access permission to the ID pool

Go to the IAM service. Select "Roles". Find Cognito_testPoolNameUnauth_Role. Click "Attach Policy". Find AmazonLexRunBotsOnly and attach it.

3. Lex call from website: here is a sample code for a website



Fill in the ID pool ID in the following code. To understand this code, you need to understand the running time of the AWS Lex 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>

      

+4


source


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

To deploy a chatbot that can interact with your site's users, there are two steps.

  1. Create and publish a chatbot:

The first step is to create a chatbot. Lex provides a simple user interface where you can customize what the user says and the corresponding response from the bot. No need to learn and AWS lambda to create a simple FAQ-like bot. The Lex interface is sufficient for this. If you are building a more powerful bot that can identify actionable details and execute some business logic as requested by the user, you need to use the AWS lambda function as an execution.

For example, if you create a bot for hotel booking and the user says:

Book me a hotel for tomorrow in London

      

Lex will provide you with booking information as shown below if you have configured slots.



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

      

Lex will send this information to your lambda function if you've enabled AWS lambda as an execution. Then your lambda function should call the hotel booking API and send a confirmation to the user.

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

  1. Integrate the bot into your site

Here you have two options:

  • The AWS SDK provides APIs for integrating a chatbot into a website. You can check this answer for more details on AWS APIs.
  • Another convenient way is to use any service, such as Kommunicate , that provides codeless integration with the Lex platform. Kommunicate is a bot + human hybrid customer support platform that provides features such as bot-to-human messaging, Actionable messages, routing rules, etc. To integrate the Lex bot into your website using Kommunicate, follow these steps:

    1. Sign up for Kommunicate, go to the bots section and select Amazon lex.
    2. Fill in the required details and click "Let this bot handle all conversations."
    3. Download the installation script from the installation section and paste it into your website.
    4. Your bot is ready to respond to your users.
+2


source


Played with AWS Lex recently and it seems like you can't really avoid using Lambda code.

At first, intercepting the validation and execution code will be lambda functions, and for any semi-decent conversation with a lexical bot you will need.

Second Chat Client: If you don't want to use the existing list of built-in chatbot integrations (currently Facebok, Twilio SMS and Slack), you need a custom implementation. A straight PHP curl might be an option (access the API directly), but I highly recommend using the standard AWMS API Gateway / AWS lambda setup to create a lex client and instead use the convenience of the SDK. This is a very flexible setting, very simple. We put together in a few days, with a minimal python code base, using the boto3 SDK, with little or no python experience.

Hope it helps!

+1


source


Custom implementation is the only way to talk to lex from your site. However, this is not as difficult as it sounds. The developer link here will help with implementation in js.

The only catch, however, is exchanging aws (IAM user) credentials in your site code. This can also be avoided by obtaining a temporary token from IAM, which will require further development.

0


source







All Articles