Preface – This post is part of the UI5 Integration Programs series.
Table of Contents
Introduction
It is not possible to directly integrate ChatGPT using a CDN (Content Delivery Network) as GPT-3 model is not hosted on any public CDN. GPT-3 is a proprietary model owned by OpenAI, and access to it is provided through the OpenAI API, which requires an API key to use.
You can use the OpenAI API in your JavaScript application by making HTTP requests to the API endpoint and using the API key. The OpenAI API provides a prompt
endpoint that allows you to send a prompt to GPT-3 and receive a response.
Here’s an example of how you might use the fetch
API in JavaScript to send a prompt to GPT-3 and log the response:
const API_KEY = 'YOUR_API_KEY'; const prompt = 'What is the meaning of life?'; fetch(`https://api.openai.com/v1/engines/davinci/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${API_KEY}` }, body: JSON.stringify({ prompt, max_tokens: 20 }) }).then(response => response.json()) .then(data => { console.log(data.choices[0].text); });
How to Integrate ChatGPT in SAP UI5
As shown in below image, we will follow three simple steps to integrate ChatGPT APIs within SAP UI5 App.
1. Get API of Open AI
We have already discussed all the steps involved regarding API creation in this article.
2. Create UI5 Project
Use Web IDE or SAP BAS and generate a simple UI5 Application using a generator.
3. Integrate ChatGPT Call
We have create a very simple view with input box, button and a text area to show output as shown in below view:
<mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:l="sap.ui.layout" xmlns:f="sap.ui.layout.form"> <Shell id="shell"> <App id="app"> <pages> <Page id="page" title="Get Answers from ChatGPT"> <content> <VBox> <Input id="idInput"/> <Button text="Get Answer" press="onPressGPT"/> <Text id="idText"/> </VBox> </content> </Page> </pages> </App> </Shell> </mvc:View>
And on the press of Button, we have written the given code in controller.js
sap.ui.define([ "sap/ui/core/mvc/Controller" ], function (Controller) { "use strict"; return Controller.extend("Test.Test.controller.Main", { onInit: function () { }, onPressGPT: function () { var that = this; const API_KEY = ''; var prompt = this.byId("idInput").getValue(); fetch(`https://api.openai.com/v1/engines/davinci/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${API_KEY}` }, body: JSON.stringify({ prompt, max_tokens: 2000 }) }).then(response => response.json()) .then(data => { that.byId("idText").setText(data.choices[0].text); }); } }); });
Output
The Output without pressing the button looks like this:
0 Comments