Website Loading ....

ChatGPT REST Integration with Salesforce using LWC

5 min read

The OpenAI developed artificial intelligence chatbot in 2022 and named it as “ChatGPT”.

Chat” referring Chatbot
GPT” stands “Generative Pre-trained Transformer”

It is used to generate human like responses. GPT-3.5 is most advanced ChatGPT version.

Salesforce and ChatGPT Integration Steps : 

Login to https://platform.openai.com/login/ for creating API Key

Salesforce Chat GPT Integration
Salesforce ChatGPT Integration Login

After login, Click on your name to see all the features available in ChatGPT. Just click on View API Keys.

Salesforce_ChatGPT_OpenAI_Integration
Saelsforce ChatGPT Integration OpenAI

ChatGPT APIKey Generation: Once click on View API keys, you will get option to create secret key from ChatGPT.then click on create new secret key to generate the unique key.

ChatGPT APIKey Generation
ChatGPT APIKey Generation process
ChatGPT Integration OpenAI
Salesforce ChatGPT Secret key Generation
Chatbot Secret key Generation Process
Chatbot Secret key Generation Process

Use the above key to authenticate with salesforce using Rest API.

Create Remote settings : Used to allow the remote site regardless of whether the user’s connection is over HTTP or HTTPS.
Goto setup -> Remote site -> Click on New Remote site settings and provide the details.

Salesforce OpenAI
Salesforce_ChatGPT_Integration_OpenAI

Create Apex Class “Salesforce_ChatGPT_Integration” to write the REST API to hit the ChatGPT server using generated secret key.

Create custom settings to store secret key instead of hard coding.

public with sharing class Salesforce_ChatGPT_Integration {
private static ChatGPTKey__c customSetting = ChatGPTKey__c.getOrgDefaults(); //Custom Setting
private static final String ENDPOINT ='https://api.openai.com/v1/completions';
@AuraEnabled
public static String getSearchData(String searchString){
try{
String seachQueryEscaped = (searchString).trim();
Http http = new Http();
String reqBody = '{"model": "text-davinci-003","prompt":"'
+seachQueryEscaped+
'","max_tokens": 4000,"temperature": 0,'
+'"stream": false,"top_p": 0.5}';
// System.debug('Query '+seachQueryEscaped+' '+reqBody);
HttpRequest request = new HttpRequest();
request.setEndpoint(ENDPOINT);
request.setBody(reqBody);
HttpResponse response = http.send(request);
if(response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' +
response.getBody());
return response.getBody();
}
return response.getBody();
}catch(Exception ex){
System.debug('Exception in Catch of Server-Side Controller '+ex);
throw new AuraHandledException(ex.getMessage());
}
}
}

Create html file for the user interface and send the Input from salesforce to ChatGPT Server.

<div class=”slds-card slds-scrollable slds-float_left” style=”width: 450px;”><header class=”slds-card__header slds-grid”>
<div class=”slds-media slds-media_center slds-has-flexi-truncate”>
<div class=”slds-media__figure”><img src=”{imageUrl}” alt=”Avatar” width=”50″ height=”50″ /></div>
<div class=”slds-media__body”>
<h2 class=”slds-card__header-title”><a class=”slds-card__header-link slds-truncate” title=”Card Title”>
ChatGpt
</a></h2>
<p class=”slds-card__header-subtitle slds-truncate” title=”Card Subtitle”>Query your doubts</p>

</div>
</div>
</header>
<div class=”scrollable-content slds-card__body slds-card__body_inner “></div>
<footer class=”slds-card__footer”>
<div class=”slds-form-element”>
<div class=”slds-form-element__control slds-input-has-icon slds-input-has-icon_right”>

<input id=”search-input-footer” class=”slds-input” type=”text” placeholder=”Enter search term” />
<div class=”slds-p-left_xx-small”></div>
&nbsp;

</div>
</div>
</footer>&nbsp;

</div>

And add below JS file.

import { LightningElement,track,api } from ‘lwc’;
import getSearchData from ‘@salesforce/apex/Salesforce_ChatGPT_Integration.getSearchData’;
import IMAGE from ‘@salesforce/resourceUrl/ChatBot’;

export default class ChatGPT extends LightningElement {
@track searchResults = [];
@track searchTerm = ”;
@api imageUrl = IMAGE;
@track showSpace = true ;
@track showSpinner = false
@track responseData ;
@api prop1;
handleKeyDown(event) {

if (event.keyCode === 13) {
// Perform search when the Enter key is pressed
this.searchTerm = event.target.value;
this.showSpinner = true
this.searchResults = [];
getSearchData({searchString:this.searchTerm})
.then(result=>{
this.showSpinner = false
let response = JSON.parse(JSON.stringify(JSON.parse(result)));
if (response.error) {
this.responseData = response.error.message;
} else if (response.choices[0].text) {
this.responseData = response.choices[0].text;
this.responseData = this.responseData.replace(/\n/g, “<br />”);
let tempScriptData = ”
tempScriptData = (response.choices[0].text.includes(‘<script>’)) ? ‘JS File: ‘
+ response.choices[0].text.split(‘<script>’)[1] : ”;
tempScriptData = this.responseTextLWCJS.replace(/\n/g, “<br />”);

this.responseData = this.responseData + this.responseTextLWCJS;
this.responseData = (this.responseData.includes(‘XML File:’)) ? this.responseData.split(‘XML File:’)[0]
: this.responseData;

this.responseData.trim();
}
console.log(‘ss’,JSON.stringify(responseData))
})
.catch(error=>{
this.showSpinner = false
console.log(‘error is ‘+error)
})
// Replace with a call to your search service
if(this.searchResults.length > 0 )
this.showSpace =false
}

}
}

Add below code in metadata xml file.

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata”>
<apiVersion>56.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordAction</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
<target>lightning__UtilityBar</target>
</targets>
<targetConfigs>
<targetConfig targets=”lightning__UtilityBar”>
<property name=”prop1″ type=”Boolean”/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

It is done. Add the component in the Utility bar to access it from the application.

Salesforce_ChatGPT_OpenAI
Salesforce_ChatGPT_OpenAI

After adding it to utility bar, go the application and use it.

 

Sruvi IT

Sruvi IT Solutions

Expert in digital transformation, SEO, and enterprise technology. Helping businesses grow through innovative IT solutions since 2018.

Leave a Comment