“Integrating ChatGPT-3 in SAP Analytics Cloud using the custom widget”. Sounds complex? Believe me! It is not. You can do it in less than 30 mins, even if you are an absolute beginner.

This blog post will explain how to create an analytic application in the SAP Analytics Cloud that can take user queries and return responses. It will involve creating a custom widget in the SAP Analytics Cloud to integrate with ChatGPT-3 using the OpenAI API. We will achieve this goal in 7 easy steps. All the relevant files can also be found on my GitHub repository here.

Step 1: Prerequisites: 

Before we proceed with the creation of a custom widget and its integration in SAC, it is important that you fulfill the following requirements.

  • Create an account on the OpenAI platform: Create an account on the OpenAI platform by visiting this URL here.
  • Getting the API key: Create a secret key in the “Build your application” section of the page by visiting this URL here.

Figure 1: The figure shows creation of secret key.

Note: Please ensure that you copy and securely save the secret key. This key will be required to make an API call in the future step.

 

Step 2: Creating custom widget: 

The custom widget created in this blog will help us integrate SAP Analytics cloud with OpenAI API. Custom widget is created with different web components and a JSON file. These web components files differ according to the custom widget use case. In this case, we need two files, i.e., “customWidget.json” and “main.js”.

I will not cover the basics of custom widget but If you would like to understand custom widgets in detail, then I recommend reading this nice blog Demystifying Custom Widgets for SAP Analytics Cloud by Pranav Kandpal.

Please select one method from Method 1 and Method 2. Note that Method 1 is recommended for quick creation of the custom widget.

 

Method 1: Plug and Play

Copy the below code and save it as a .json file to your local system with the name “customWidget” and proceed to Step 3.

{
  "eula": "",
  "vendor": "Danish",
  "license": "",
  "id": "com.danish.sap.sac.chatgpt",
  "version": "1.0.0",
  "name": "chatGPT SAC",
  "newInstancePrefix": "chatGPTInSAC",
  "description": "A custom widget to integrate chatGPT3 in SAC Analytic application",
  "webcomponents": [
    {
      "kind": "main",
      "tag": "custom-widget",
      "url": "https://dmeraj.github.io/integrating-chatGPT3-in-SAC/main.js",
      "integrity": "",
      "ignoreIntegrity": true
    }
  ],
  "properties": {
		"width": {
			"type": "integer",
			"default": 1
		},
		"height": {
			"type": "integer",
			"default": 1
		}
  },
  "methods": {
		"post": {
			"description": "Wrapper for jQuery post",
			"parameters": [
				{
					"name": "APIKey",
					"type": "string",
					"description": ""
				},
				{
					"name": "endPoint",
					"type": "string",
					"description": ""
				},
				{
					"name": "prompt",
					"type": "string",
					"description": ""
				}
			],
			"returnType": "string"
		}
  },
  "events": {
  }
}

 

Method 2: 

  • Copy the code below and Save it as .js file to your github. Ensure that the code is hosted and can be accessed from the URL.
    var ajaxCall = (key, url, prompt) => {
      return new Promise((resolve, reject) => {
        $.ajax({
          url: url,
          type: "POST",
          dataType: "json",
          data: JSON.stringify({
            model: "text-davinci-002",
            prompt: prompt,
            max_tokens: 1024,
            n: 1,
            temperature: 0.5,
          }),
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${key}`,
          },
          crossDomain: true,
          success: function (response, status, xhr) {
            resolve({ response, status, xhr });
          },
          error: function (xhr, status, error) {
            const err = new Error('xhr error');
            err.status = xhr.status;
            reject(err);
          },
        });
      });
    };
    
    const url = "https://api.openai.com/v1";
    
    (function () {
      const template = document.createElement("template");
      template.innerHTML = `
          <style>
          </style>
          <div id="root" style="width: 100%; height: 100%;">
          </div>
        `;
      class MainWebComponent extends HTMLElement {
        async post(apiKey, endpoint, prompt) {
          const { response } = await ajaxCall(
            apiKey,
            `${url}/${endpoint}`,
            prompt
          );
          //console.log(response.choices[0].text);
          return response.choices[0].text;
        }
      }
      customElements.define("custom-widget", MainWebComponent);
    })();
  • Copy the code from method 1 and change the “url” object in the property “webcomponents” to your own hosted URL, as shown in fig. 2. Save the file as “customWidget.json” and proceed to Step 3.

Figure 2: The figure shows the edit required if the hosting url is changed.

 

Step 3: Adding the custom widget in SAC.

Add custom widget in SAC by navigating to Analytic application -> Custom widgets and click on ‘+’ icon as shown in the fig.3. Select the file from local system and click “OK” as shown in fig. 4.

Figure 3: The figure shows adding of the custom widget in SAC.

 

 

Figure 4: The figure shows uploading json file in SAC.

 

Step 4: Adding the custom widget to Analytic designer. 

Add the custom widget to the application designer by following the steps in fig 5. 

Figure 5: The figure shows adding custom widget in analytic designer.

 

Step 5: Creating a User interface in Analytic designer.

Add additional widgets to the analytic designer for creating a basic UI and name the widgets like those shown in fig 6.

Figure 6: The figure shows the required widget to create a basic UI.

The final UI should look like as shown in the fig. 7.

Figure 7: The figure shows the overview of the UI.

Note: ChatGPT-3 logo is optional.

 

Step 6: Adding a script to the onClick event

Add the script below to the “button_submit ” onClick event. Replace the SECRET_API_KEY with your secret API key created in Step 1. 

var endpoint = "completions";

var APIKey = "SECRET_API_KEY";

var prompt = InputField_prompt.getValue();

var response = chatGPTInSAC_1.post(APIKey,endpoint,prompt);

Text_response.applyText(response);

//console.log(["output", response]);

 

Figure 8: The figure shows the script for “onClick” event in button.

 

Step 7: Testing the integration

Congratulations!!! ChatGPT-3 integration in SAP Analytics Cloud is completed. Go ahead and type your query and get response from chatGPT-3 as shown in fig 9.

Note: If you face issues, such as output is not visible, make the size of “Text_response” widget a bit bigger. Additionally, try to get shorter responses first and then gradually tune the rest of the UI to fit the requirement.

Figure 9: The figure shows Analytic application giving response from ChatGPT-3.

 

Conclusion: In this blog, we created an analytic application and integrated it with OpenAI API using custom widgets. The analytic application has a user interface through which users can interact with the ChatGPT-3. The existing application can be extended and tuned to fit specific use cases. This blog can also give an idea about creating custom widgets to integrate with external APIs.

If you find this blog useful then, please like this blog post and follow me for contents related to SAP Analytics Cloud. If you have any questions or feedback, please leave a comment below.

 

References and Further study on similiar topic:

Quickly integrate Sap Analytics Cloud with other systems using custom widget.

Demystifying Custom Widgets for SAP Analytics Cloud

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x