Skip to Content
Technical Articles

Displaying KPI Analytics in SAP CAI Chatbot Message

Hello Everyone,

Welcome to my another interesting blog ” Displaying Analytics or Dynamic Chart in SAP Conversational AI” as response. Hold on hold on if you are SAP CAI fan then you might’ve started thinking when chart control got released in SAP CAI for message. Yes you are right, there is no standard chart control available in SAP CAI as of now. Just to kill your all curiosity you have to read this blog. I promise it’s really worthy 😀

So How i got this idea to bring dynamic chart or analytics in SAP Conversational AI as response?

One day i was surfing through different question in SAP Conversational AI and one question i found how to display kpi/chart in SAP CAI Chat bot. I found this question pretty interesting because there is no standard message control for displaying chart in conversational AI. Who doesn’t love analytics people love it in SAP Fiori app and the way Chatbot is growing as Enterprise Assistant people would love to see KPI/Analytics in Chatbot too.

But how it is possible as there is no standard chart control available in SAP Conversational AI?

“when there is a will there’s a way”

Have you heard about image chart API, Image chart is a great work around in this case, Why? Because SAP CAI have standard image control as message/response.

How Image Chart API works?

You can generate image url dynamically with different chart and data point just by passing all the parameter with the help of Image Chart server, it is very similar to google image chart. It allows you to create dynamic charts using nothing more than a URL string and that is best part because we know a image url with chart works perfectly in SAP CAI. To get the feeling copy the below url and paste in the browser and hit.

https://quickchart.io/chart?width=500&height=300&c={type:'bar',data:{labels:['January','February','March','April',
'May'],
datasets:[{label:'Dogs',data:[50,60,70,180,190]},{label:'Cats',data:[100,200,300,400,500]}]}}

To explore it in details play with it by changing the data point so it will give you good idea how you can play with it. For more details have a look at the official site.

There are another similar type of solution image chart.

Lets have a look how it looks  in Embedded SAP CAI Webchat in Fiori Launchpad

Let’s get into the action, how we are going to implement it.

As i mentioned we will be using quick chart api for generating dynamic image chart and quick chart is open source that means you also can host this in SAP Cloud Platform and even docker version is also available, so you can also directly deploy to cloud foundry with very minimal effort. In this example we are going to get sales data from a particular odata service and then pass those data self hosted quick chart api server in SAP Cloud Platform CF to generate the dynamic image chart with url which will be used in SAP CAI Response using node.js based web hook message builder.

Let’s have a look at Technical Architecture

As you can see in the architecture chatbot has been designed in SAP Conversational AI which is hosted as Webchat in Fiori launchpad. Sales related analytics data is coming from SAP S/4HANA as a odata service which is being called in  node.js based webhook application for building the message. For generating dynamic chart, docker container of quickchart has been deployed into SAP Cloud Platform Cloud foundry.

Let’s break this whole stuff into small pieces, so that it would be easy to understand.

Step 1: Deploying the docker container of quickchart.

Docker image of quickchart is located here

In order to deploy docker image of quickchart as a container into SAP Cloud Platform just login to CF CLI and type below command

cf push quickcdocker –docker-image ianw/quickchart

On successful deployment you will be able to open the application just like below and able to generate image based chart.

Step 2: Analysis the Sales by Region OData service which will be base of our chart here.

N.B Just for tutorial or demo purpose i have used HANA Shine content based Sales by region odata, but you can use actual odata service

Below is how my odata service looks like

Step 3: Developing Node.js based Web hook application to build message / response for SAP CAI Chat bot

As i told you our main goal is to use quickchart api to generate url of chart image dynamically so this node.js application will fetch all the data point from above odata service and use those data point to generate url for image chart. Please have a look at Github repository for code snippet.

For deploying node.js based application to cloud foundry have a look at this blog.

Step 4: Designing Chatbot in SAP CAI

If you are beginner and just have started exploring SAP Conversational AI then i would suggest you to go through this  amazing tutorial

Here is my intent

My Skill’s Requirement, Chat bot will ask what type of chart user want to see, in this example two options i have maintained as entity (pie chart and donut chart)

In the action use node.js based Web hook and below is how action looks like

Step 5: Deploying this Chat bot in Fiori Launchpad, Please follow this  blog

Once all the steps are finished you can test it, Below is the video of my testing.Please have look. I hope you enjoyed this trick to bring or displaying chart in SAP CAI. If you liked this blog please like comment and share with your colleague.

 

Regards,

Sudip

 

 

 

 

 

 

10 Comments
You must be Logged on to comment or reply to a post.
  • Nice blog as usual! I have a Non-technical question though –

    Is SAP Conversational AI is absolutely free for any environment like Dev/Prod? Or is it only free for SAP-internal use particularly? I am referring below the link to understand since you are SAP employee you might have clear visibility on it, not sure. Since I left SAP in 2008, almost a decade now and more depend on SAP Sales customer Executives for pricing model for every product release. 🙂

    https://cai.tools.sap/pricing

     

    Thanks in adv.

    Amit Lal

    • Hello Amit,

      No it is not free, I am using here developer version which is free for everyone. SAP CAI come as service in SAP Cloud Platform Cloud Foundry Model, as a customer or productive usage you have to subscribe. If you want to see the cost i would suggest you to have a look at pricing calculator as well as connect with SAP CAI Team. They can give better insight, i am not in a position to comment on pricing but as per pricing calculator whatever data i am getting that only i can provide and below is how it looks like from pricing point of view as per Estimator tool.

      Regards,

      Sudip

      /
  • Hi Sudip,

    Thanks for the blog.

    I am following the same steps you have mentioned, but though I get some error while running. I have deployed the node.js app to Cloud Foundary. When I am running the chat bot locally (i.e ngrok ) I am able to get the chart in ChatBot.Can you please help me with this?

    And I have one doubt like should I put any authentication in webhook, if yes what kind of auth it will be?

    /
      • var http = require('http');
        var express = require('express')
        var request = require('request')
        const bodyParser = require('body-parser')
        const turl = require('turl')
        var app = express()
        const port =  process.env.PORT || 3000
        app.use(bodyParser.json())
        app.use(express.static(__dirname));
        var tempreq;
        //var url = 'https://services.odata.org/V3/Northwind/Northwind.svc/Employees';
        var url = 'http://vmXXX.sapls.local:8000/sap/opu/odata/sap/XXXX_XXX/EmployeeHeaderSet';
        app.post('/',async(req,res)=>{
            var typeofChart = "pie";//req.body.ctype;
            var demourl = url;
         var headers = {
               'Content-Type': 'application/json',
               'Accept': 'application/json',
              'Authorization': 'Basic YmFkaHVzaGE6YWtodGhjYXI=',
               "x-csrf-token" : "Fetch",
           };
           console.log("Passed")
           var options = { method: 'GET',
             url: demourl,
             headers: headers 
              };
              request(options, function (error, response, body) {
                if(error){
                  console.log(error);
                }
                if (!error && response.statusCode == 200) {
                    // Print out the response body
                    //console.log(body)
                    var resultData = JSON.parse(body);
                    //console.log(resultData);
                    var datalength = resultData.d.results.length;
                    // var labels1 = new Array(),
                    //     datapt = new Array();
        
                    var allData = [
                                      ["NOVIGO US",0],
                                      ["NOVIGO INDIA",0],
                                      ["NOVIGO GERMANY",0],
                                      ["NOVIGO CANADA",0],
                                      ["NOVIGO AUSTRALIA",0],
                                      ["NOVIGO TURKEY",0],
                                      ["NOVIGO SPAIN",0]
                                  ];
        
        
                    var labelSet = new Set();
                    for (i=0;i<datalength;i++){
        
                      if (resultData.d.results[i].CompanyCodeText != '' && resultData.d.results[i].EmpId != '') {
                        labelSet.add(resultData.d.results[i].CompanyCodeText);
                        var cname = resultData.d.results[i].CompanyCodeText;
                        console.log(cname);
                        var innerIndex,outerIndex;
                        outerIndex = allData.findIndex(function(sub){
                          innerIndex = sub.indexOf(cname);
                          return innerIndex !== -1;
                        });
                        console.log(allData[outerIndex]);
                        allData[outerIndex][1] = allData[outerIndex][1] + 1; 
                      }
        
                    }
        
        
        
                    var labelArray = [];
                    var labelData  = [];
        
                    for (let j = 0; j< allData.length; j++) {
                        labelArray.push(allData[j][0]);
                        labelData.push(allData[j][1]);    
                    }
        
                    var chartjson = {type:typeofChart,data:{labels:labelArray, datasets:[{data:labelData}]}};
                    console.log(allData);
                      var shrturl;
                      var imageUrl = 'https://novigochart.cfapps.eu10.hana.ondemand.com/chart?c='+JSON.stringify(chartjson).toString();
                      turl.shorten(imageUrl).then((res1) => {
          //console.log(res1);
          finalJson = {
            replies: [{
              type: 'picture',
              content: res1
            }], 
            conversation: {
              memory: { key: 'value' }
            }
          }
          // var str = JSON.stringify(finalJson);
          res.send(finalJson);
          //res.send("Hello There");
        
        }).catch((err) => {
          console.log(err);
        });
        } else {
                    res.send('Error happened')
                }
            })
        })
        
        app.listen(port, () => { 
            console.log('Server is running on port '+port) 
          })
        
        
        
        
    • hello Akhthaar,

      It Shine Application sales by region xsodata which come in hana mdc trial as part of neo sap cloud platform.

       

      Regards,

      Sudip

  • Hi Sudip Ghosh,

    Greetings for the day…

    Thanks much for nice blog… I am tring to display chart with hardcoded data as shown in below code.  I am facing one issue while using chart on SAP CAI bot..

    When run bot I am getting below error (chart is not loading)

     

    When I am trying to run url in browser its giving below error:

    Please guide what I am doing wrong..

    Thanks-

    Abhishek