Introduction
Natural Language Processing (NLP), generative Artificial Intelligence (AI), and other foundation models have completely altered the flow of business processes. Generative AI has increased productivity and efficiency, reduced costs, and created new growth opportunities by automating tasks previously performed by humans.
What is ChatGPT?
You can read more about ChatGPT here.
Salesforce Integration with ChatGPT
Now let’s integrate with our ORG.
Step 1: Create APIKey from the OpenAI platform.
Login to https://platform.openai.com/login/
Click on View API Keys
- Click on Create new secret Key, and API Key will be generated, we will utilize this API Key to hit the Chat GPT endpoint.
Step 3: Now add Remote Site Settings.
Step 4: Now Create Apex Class ChatGPTController.cls to hit the ChatGPT API
/**
* @description :
* @author : Shiv Shanakr
* @group :
* @last modified on : 02-07-2023
* @last modified by : Shiv Shankar
**/
public with sharing class ChatGPTController {
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());
}
}
}
Step 5: Now Create LWC ChatGPT.html
<!-- @description : @author : shiv@altdigital.com @group : @last modified on : 02-07-2023 @last modified by : shiv@altdigital.com --> <template> <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} width="50" height="50" alt="Avatar" /> </div> <div class="slds-media__body"> <h2 class="slds-card__header-title"> <a href="javascript:void(0);" 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 "> <template if:true={responseData}> <lightning-formatted-rich-text disable-linkify value={responseData}></lightning-formatted-rich-text> </template> <template if:true={showSpace}> <br/> <br/> <br/> </template> <template if:true={showSpinner}> <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner> </template> </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 type="text" id="search-input-footer" class="slds-input" placeholder="Enter search term"
onkeydown={handleKeyDown} /> <span class="slds-icon_container slds-icon-utility-down slds-input__icon
slds-input__icon_right multi-select-combobox__icon" title="Click to open the dropdown" ><div class="slds-p-left_xx-small"> <lightning-icon icon-name="utility:right" size="xx-small" alternative-text="Click here" class="slds-icon slds-icon--selected slds-icon--x-small slds-icon-text-default" > </lightning-icon> </div> </span> </div> </div> </footer> </div>
import { LightningElement,track,api } from 'lwc'; import getSearchData from '@salesforce/apex/ChatGPTController.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 } } }
<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>
Step 6: Now add the component to the “Utility Bar” of any application.
Now it’s done. We have successfully integrated Salesforce with ChatGPT.