Start building your own chatbot now

“People don’t buy what you do. They buy why you do it.” – Simon Sinek

With the changing business environment, enhanced user experiences, an intelligent state-of-the-art enablement and intuitive service, I recently became interested in chatbots and how they can serve our customers better.

Here’s how! I’d like to present a use case, where an e-commerce customer runs an SAP C/4HANA service cloud application to manage its comprehensive sales service, intelligent recommendations, offline mobility, etc. In order to manage its customer care center efficiently, I’d like to propose an SAP Conversational AI based chatbot.

sap-conversational-ai-with-iu5

Before you start, please familiarize yourself with the SAP Conversational AI API Reference to know more about connectors. Since you can design the chatbot’s interface in several ways, please find this CodePen link. For a successful integration, be sure to provide the correct token number, user slug, request token etc. Also note that the token number may be automatically changed by the software, so a chatbot interaction and integration that works now may require you to update the token after a month in order to keep working successfully. Please find a link to the above sample code in the GitHub repository.

In this article, I’ve developed a textual intelligent chatbot and explained the steps to integrate it with SAP Web IDE.  I’ll be using SAP Conversational AI to create the chatbot and integrate and render it in UI5. So friends, let’s get started!

SAP Web IDE for the frontend

I decided to use SAP Web IDE to develop the frontend for the project because SAP Web IDE allows fast, yet robust development of sites that can be deployed easily. SAP Web IDE was the perfect fit for this learning project.

Assumptions

  • You have created your chatbot in SAP Conversational AI. If not, please follow this tutorial.
  • You have a basic knowledge of REST APIs.

Integration and chatbot rendering

Step 1: Invoke the SAP Conversational AI REST API to pass your user slug and token.

a) Redefine an onAfterRendering method in your main controller file. Here, you first need to invoke your SAP Conversational AI chatbot instance.

In SAP UI5, to read the uuid (universally unique identifier) of your bot account created in SAP Conversational AI, you need to call a REST API (detailed in step b. below). In addition, you need to initialize the event for your chat button click. This event initialization opens the SAP UI5 based chat window as soon as the application is launched. This is an entirely optional step that determines how you want your chat window to open.

In my case, I’m using a toggle button to open/close the chat window. However, on the initial launch of application, it would open as well.

/** method onAfterRendering redefined for bot management and ui rendering
*/
onAfterRendering: function () {

        this.getBot(); //get user uuid of your bot account in cai.tools.sap
        sap.ui.getCore().byId("chatBtn").attachPress(this.openBot.bind(this)); 
             //attaching press to open chat window			this.detailContent=this.getView().getContent()[0].getContent()[0].getCurrentMasterPage().getContent()[0].getCurrentDetailPage().getCurrentDetailPage();
},

b) Invoke the REST API call to get the user unique ID or uuid that will later be used for interaction between the UI5 bot interface and SAP Conversational AI based intents.

The call to the SAP Conversational AI based chatbot is just like invoking an RFC via a web service. For simplicity, just understand your UI5 application as A and the chatbot based in another software as B. You need to invoke the chatbot instance in B’s software from A’s code. This interaction or integration is at service level. Hence, you guessed it right? You can access B by a web service passing the necessary parameters like user slug and service URL.

What are the parameters required to access B via a web service? First, you need to log in to your SAP Conversational AI account, then select your bot, and go to Settings. You can use the below image for your reference.

sap-conversational-ai-chatbot-training

c) After navigating to your bot settings, click Tokens in the menu bar on the left. There, you’ll find your user slug and request token.

sap-conversational-ai-chatbot-settings

d) The request token serves as the authorization key to be passed for invoking the chatbot instance.

The second required parameter is the user slug, which can also be copied from the above image. The only thing left is to form the complete service URL:

Service URL = { Callback URL + user slug }

Here, to read our chatbot, our callback URL is https://api.cai.tools.sap/auth/v1/owners + user slug found in the bot settings.

To know how to find the callback URL, please see the API guide. After you have the required parameters, you can refer to the below code to invoke the chatbot in SAP UI5.

/** method getBot defined to 
* Get your SAP Conversational AI user account uuid
* Unique key helps you load your bots into ui5
**/
getBot: function () {
            var that = this;
            //check your user-slug in SAP Conversational AI 
            $.ajax({
                type: "GET",
                url: "https://" + "api.cai.tools.sap/auth/v1/owners/manisha-madhwani",
            
                headers: {
"Authorization": "63fea95075c0084de2f5ea663371c475"//request token
                },
                success: function (data) {
                    that.uuid = data.results.owner.id;
                },
                error: function (data) {}
            });

},

Step 2: Create a chat window as a popover in your UI5 application.

You can traditionally use an SAP UI5 based popover and render the sender/receiver icons using a standard or your own custom icon. I have used a custom CSS icon from CodePen to provide a better animation. Please refer to the below code.

sap.ui.jsfragment("ui.ui.view.ChatBot", {
    // defines the UI of this View
    createContent: function() {
        var oLayout=new sap.ui.layout.VerticalLayout().addStyleClass("window");
        var oHLayout=new sap.ui.layout.HorizontalLayout("history").addStyleClass("history");
        var oUrl="https://"+"sdlambert.github.io/loremipsum/img/smiling36.svg"; //smilie icon next to sender input box
        var oImg=new sap.m.Image({src:oUrl, height:"20%", width:"20%"}).addStyleClass("middle");
        var oTextArea=new sap.m.Input("chat",{placeholder:"Write a reply",autofocus:"autofocus",valueLiveUpdate:false}).addStyleClass("input middle");
        var oLabel=new sap.m.Text("oLabel1",{textAlign:sap.ui.core.TextAlign.End}).addStyleClass("rightLabel");
        oHLayout.addContent(oLabel);
        oLayout.addContent(oHLayout);//Chat Input by user display
        oHLayout=new sap.ui.layout.HorizontalLayout({width:"20%"}).addStyleClass("middle");
        oHLayout.addContent(oTextArea);
        oHLayout.addContent(oImg);
        oLayout.addContent(oHLayout);//Chat area for user
        var oForm = new sap.ui.layout.form.SimpleForm({
            maxContainerCols: 1,
            editable: true,
            layout: "ResponsiveGridLayout",
            minWidth: 1024,
            visible: true
        }).addStyleClass("sapUiNoContentPadding");
        oForm.addContent(oLayout);
        oForm.addContent(oHLayout);
        var dialog=new sap.m.ResponsivePopover({title:"Chat Your Bot",contentHeight:"55%",contentWidth:"25%",placement:sap.m.PlacementType.Top});
        dialog.addContent(oForm);//popover to display text and chat input area
        return dialog;
    }
});

Invoke your chatbot by registering the Enter key with code 13 for chat input. This will enable a bot-user chat interactive display when the Enter key is pressed.

/** method to openbot popover
         * Open Bot Fragment
         * Bot over footer button
         **/
        openBot: function (oEvent) {
            if (!this.oChatBot) {
                this.oChatBot = sap.ui.jsfragment("ui.ui.view.ChatBot", this);
                this.oChatInput = this.oChatBot.getContent()[0].getContent()[1].getContent()[0];
                this.oChatInput.attachLiveChange(this.addConversation.bind(this));
            }
            var oModel = new sap.ui.model.json.JSONModel({
                data: {}
            });
            this.oChatBot.setModel(oModel);
            this.oChatBot.openBy(this.detailContent.getFooter().getContentRight()[1]);
            // Init listeners
            this.chatInput = document.getElementById("chat");
            this.chatInput.addEventListener("keyup", this.parseText.bind(this), false);
            this.history = document.getElementById("oLabel1");

            this.isTyping = false;
        },

After completing this step, you’ve configured your bot to UI5 and created an interface for interactions.

Step 3: Fetch the response of the user chat input based on the NLP (Natural Language Processing) intent created in SAP Conversational AI.

To achieve a successful reply from the intent, you need to pass the developer token. You can get this by logging in to SAP Conversational AI, navigating to your bot, selecting Settings, and then clicking Tokens. Also, you need the service URL that you can find in your bot settings under Options. In addition, you need the uuid from step 1. Hey, but what we forgot in this parameter packaging, most importantly, is the user data from the chat window, based on which intent the  bot makes a reply.

To pass the chat message from UI5 to SAP Conversational AI, you need a JSON object containing three things:

  • Message JSON object, consisting of:
    • Type: message type as text
    • Content: message from the chat window
  • Conversation ID: you can give any alphanumeric number to this property
  • Log_level: I’ve provided the info type. To know more about this, see Dialog Endpoints in the API Reference.

Please find sample code below from respondTo method definition:

// simulated delayed response
            delay = Math.ceil(Math.random() * (responseLength + 1) * 1000) + 2500;
            if (msgLength > 0) { //if user has inputted message then
                var _data = {
                    "message": {
                        "type": "text",
                        "content": message
                    },
                    "conversation_id": "test-1533969037613",
                    "log_level": "info"
                };
                var that = this;
                $.ajax({
                    type: "POST",
                    data: JSON.stringify(_data),
                    url: "https://" + "api.cai.tools.sap/build/v1/dialog",//bot connector callback url you will find under settings>options
                    contentType: "application/json",
                    path: "/build/v1/dialog",
                    scheme: "https",
                    headers: {
                        "Authorization": "Token 8b83f0f2f4cee9193d4b371d53dad8b7",//developer token
                        "x-uuid": that.uuid
                    },
                    success: function (data) {
                        // do what you need to 
                        that.pqaBotConversation = data;
                        that.createMessage("bot", data.results.messages[0].content, delay);
                    },
                    error: function (data) {
                        that.botError = data;
                    }
                });

After completing this step, you’ve successfully integrated SAP UI5 with the SAP Conversational AI chatbot. Now, the user is able to interact using your chat window in UI5, but the reply received from the bot is yet to be displayed. See step 4 on how to achieve this.

Step 4: Create a UI response from the bot message content received in step 3’s REST API call to the SAP Conversational AI based chatbot.

Here, I have simplified icon type, alignment, and text alignment display into two as bot and user categories. Please refer to the below code.

/**
         * createMessage creates a message with an optional delay and posts it to the
         * .chat_history window.
         *
         * @param  {String} from       - "user", "bot" class
         * @param  {String} message    - message
         * @param  {Number} delay      - delay in MS
         *
         */
        createMessage: function (from, message, delay) {
            var p, // paragraph element for message
                img, // image for avatar
                innerDiv, // inner div to hold animation and avatar
                outerDiv, // outer div for clearing floats
                animationSequence, // class list for animation
                position; // left or right

            // paragraph
            p = document.createElement("p");

            // img
            img = document.createElement("img");

            if (from === "bot") {
                img.src = "https:"+"//sdlambert.github.io/loremipsum/img/helmet1.svg";
                position = "left";
            } else if (from === "user") {
                img.src = "https:"+"//sdlambert.github.io/loremipsum/img/user168.svg";
                position = "right";
            }

            img.classList.add("avatar", "middle", position);

            // inner div
            var innerDiv = document.createElement("div");
            innerDiv.appendChild(img);
            innerDiv.classList.add(from);
            var p;
            // add animation, remove animation, add message
            if (delay) {
                this.addAnimation(innerDiv);
                var that = this;
                setTimeout(function () {
                    that.removeAnimation(innerDiv);
                    p.appendChild(document.createTextNode(message));
                    innerDiv.appendChild(p);
                    that.history.scrollTop = that.history.scrollHeight;
                    that.isTyping = false;
                }, delay);
            } else {
                // no delay, just post it
                p.appendChild(document.createTextNode(message));
                innerDiv.appendChild(p);
            }

            //outer div
            outerDiv = document.createElement("div");
            outerDiv.appendChild(innerDiv);
            outerDiv.classList.add("full");

            // history
            this.history.appendChild(outerDiv);
            this.history.scrollTop = this.history.scrollHeight;

        },
        

Step 5: Add animations to your chat window.

This step is entirely optional. However, animations make chat look lively, dynamic, and appealing to the user! In order to add animations to your chat window, you can use any method. For example, you might want to show a busy indicator after a message is sent either from the bot or user. I’ve rolled the respective icon upon the user’s message display and displayed a busy indicator by appending dots for a certain delay of seconds. After a timeout, don’t forget to remove any animations used! 😊

Please refer to the below code to see how I added an animation to my chat interface in the UI5 application.

/**
         * addAnimation adds the "typing" animation to element by appending the
         * animation sequence divs to the target element.
         *
         * @param {HTMLElement} element  - the target Element
         *
         */
        addAnimation: function (element) {
            var animationSequence = ["one", "two", "three"];

            animationSequence.forEach(function (animationClass) {
                var newDiv = document.createElement("div");
                newDiv.classList.add("bouncer", animationClass);
                element.appendChild(newDiv);
            });
        },
        /**
         * removeAnimation removes the "typing" animation by removing all of the
         * child divs of the target element.
         *
         * @param  {HTMLElement} element - the target Element
         *
         */
        removeAnimation: function (element) {
            var i = element.childNodes.length - 1;

            for (; i >= 0; i--)
                if (element.childNodes[i].tagName === "DIV")
                    element.removeChild(element.childNodes[i]);
        },
        

After completing this step, you’ll be able to exchange messages between UI5 and an intelligent chatbot created using SAP Conversational AI. However, if you’re using the icons/animations from my example, you need to do one last step.

Step 6: Add relevant style classes.

Add relevant style classes for:

  • User and bot images in the chat display to appear as icon size.
  • User and bot image alignment respectively to left/right.
  • User and bot text alignment respectively to the left/right of the chat window.
  • Chat window size.
  • Smile/send icon alignment to the input chat box.
.chat_input {
  height: 18px;
}

.chat_input img {
  display: inline-block;
  margin: 7px 2px;
}
img.avatar.middle.right {
    height: 1rem;
}
img.avatar.middle.left {
    height: 1rem;
}
.right {
  float: right;
}

.left {
  float: left;
}

.user,
.bot {
  font-family: 'Roboto', sans-serif;
  border-radius: 11px;
  padding: 3px;
  font-size: 15px;
  display: block;
  margin: 4px;
  vertical-align: middle;
  overflow-x: hidden;
  max-width: 97.5%;
}

Conclusion

Chatbots are a great driving force these days, especially in areas where customer-care centers or call centers are being used to serve a large number of customers, and where response time needs to be optimized so that a business can serve larger and faster customer needs. Since maintaining a good customer base in this ever-changing world has always been a challenge, intelligent bots are going to be the future of the sales and service space.

What’s next?

Automation is key to solve many real-time business problems of course only through artificial intelligence to make life simpler and label us hi-tech humans. These intelligent bots are also venturing into the space of audio interactions (apart from textual interactions) by integration with another level of Alexa or Google assistant.

Want to build your own conversational bot? Get started with SAP Conversational AI !

Follow us on
There are currently no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.