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.

ChatGPT is one of the generative AI models that has sparked global interest with its powerful deep learning algorithms.

What is ChatGPT?

Every developer nowadays is asking this question. They must have heard about it from friends or colleagues or seen it on social media. So now I’ll try to familiarize you with it and provide a use case for Chat GPT integration in Salesforce. OPENAI launched Chat GPT, a chatbot, in November 2022. It is based on the Open AI GPT – 3.5 family of large language models and can be trained using both supervised and reinforcement learning techniques. OPENAI provides support for Chat GPT. (founded in San Francisco in late 2015 by Sam Altman and others).

ChatGPT for blog
A family of models with different capabilities and price points powers the OpenAI API. You can customize our base models for your specific use case with fine-tuning.
ChatGpt-2

You can read more about ChatGPT here.

Salesforce Integration with ChatGPT

I use LWC to create and display user query results after integrating the ChatGPT service into my Org. In addition, I have consist of this component in the Utility Bar so that it is accessible from any page. In my scenario, I’m using the GPT3 model. You will consist of two parameters in your request body: Top P and Temperature.
Where Top p (short for “top probability“) is a parameter that controls the model’s likelihood of selecting the most likely next word at each stage of the generation process, it specifies the probability that the model will only consider the most likely next word rather than sampling from the entire distribution of possible next words. By increasing the value of top p, you can make the model less likely to consider less likely words, making its output more deterministic.
 
On the other hand, Temperature is another parameter that controls the randomness of the generated text. It functions by scaling the model’s logits (prediction scores) and then using the softmax function to transform them into probabilities. A greater temperature will lead to a softer, more diffuse probability distribution, increasing the likelihood that the model will select less likely terms and provide more original and varied output. A tougher, more pronounced probability distribution will come from a lower temperature, making the model’s output more deterministic and predictable.

Now let’s integrate with our ORG. 

Step 1: Create APIKey from the OpenAI platform.

ChatGpt-3
  • Click on Create new secret Key, and API Key will be generated, we will utilize this API Key to hit the Chat GPT endpoint.
chatGpt-4
  •  
Step 2: Now come to Salesforce and create one custom setting to store this API Key.

Step 3: Now add Remote Site Settings.

ChatGpt-5
ChatGpt-6

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>
– ChatGPT.js
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 } } }
– ChatGPT.js-meta.xml
<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.

ChatGpt-11

Now it’s done. We have successfully integrated Salesforce with ChatGPT.

ChatGpt-12