Chat GPT Integration in Salesforce

Chat GPT Integration in Salesforce

What is Chat GPT? Nowadays this question comes across every developer. They must have heard this from their friends or colleagues or may have seen some posts on social platforms. So now I will try to get you familiar with it and use case for Chat GPT Integration in Salesforce.

Chat GPT is a chatbot launched by OPENAI  in November 2022. It is built on top of Open AI GPT – 3.5 family of large language models and is fine with both supervised and reinforcement learning techniques. Chat GPT is backed up by OPENAI (founded in San Francisco in late 2015 by Sam Altman and others)

Models

As we all know AI is all based on Models and we all know a Model is a program that can find patterns or make decisions from a previously unseen dataset. So, OpenAI API is powered by a family of models with different capabilities and price points. You can also customize our base models for your specific use case with fine-tuning.

Generally, OPENAI provides three bases that further hold subcategories of the same type.

  1. GPT-3   A set of models that can understand and generate natural language. For ex: text-davinci-003 , text-curie-001.
  2. Codex (Limited beta)   A set of models that can understand and generate code, including translating natural language to code. For ex: code-davinci-002:
  3. Content filter    A fine-tuned model that can detect whether text may be sensitive or unsafe.

You can read more about Chat GPT here.

How to use Chat GPT?

Check the below session on how we can create an Apex trigger using chat GPT and test class within a minute for Salesforce.

Chat GPT Integration in Salesforce

I integrate chat GPT service within my Org and use LWC to create and display User query results. Also, I have added this component in my Global Action so it will be available at every page. I am using the “text-davinci-003” model in my scenario. While making your request body you will provide two parameters Top_P and Temperature. 

Where Top_p (short for “top probability”) is a parameter that controls the likelihood of the model choosing the most likely next word at each step of the generation process. Specifically, it determines the probability that the model will only consider the most likely next word, rather than sampling from the full distribution of possible next words. By setting a higher value for top_p, you can make the model less likely to consider less likely words and therefore more deterministic in its output. 

On the other hand Temperature is another parameter that controls the randomness of the generated text. It works by scaling the logits (prediction scores) of the model before applying the softmax function to convert them into probabilities. A higher temperature will result in a softer, more diffuse probability distribution, which in turn will make the model more likely to choose less likely words and produce more creative and varied output. A lower temperature will result in a harder, more peaked probability distribution, which will make the model more deterministic and predictable in its output.

Now let’s integrate with our ORG.

Steps

1: Create a LWC component  which will provide a chat window-like interface.

<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>
</template>

2:  Handle enter hit on your input box and make a call to your Apex handler for getting User            Query Result

handleKeyDown(event) {
    
      if (event.keyCode === 13) {
        // Perform search when the Enter key is pressed
        this.searchTerm = event.target.value;
        this.showSpinner = true
        this.searchResults = [];
        getQueryData({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)
         })
    
        this.searchResults = results;
        if(this.searchResults.length > 0 )
          this.showSpace =false
      }
    
  }

3 : Hit OpenAI endpoints by using a secret Key at server side.your request will look like this.

 Http http = new Http();
            String reqBody = '{"model": "text-davinci-003","prompt":"'
                +trimmedQuery+
                '","max_tokens": 4000,"temperature": 0,'
                +'"stream": false,"top_p": 1}';
            System.debug('Query '+trimmedQuery+' '+reqBody);
            HttpRequest request = new HttpRequest();
            request.setEndpoint(ENDPOINT);
            request.setMethod('POST');
            request.setHeader('Authorization', 'Bearer '+String.escapeSingleQuotes(key).trim());
            request.setTimeout(120000);
            request.setHeader('Content-Type', 'application/json;charset=UTF-8');
            request.setBody(reqBody);
            HttpResponse response = http.send(request)

In the end your component looks like this

Chat GPT Integration in Salesforce
Chat GPT Integration in Salesforce

You can get the full code here.

Implications of ChatGPT to Salesforce developers

For junior developers, ChatGPT could be used to accelerate their coding skills by creating a prompt and then looking at the ChatGPT answer. The other angle is for them to gain skills as a Prompt Engineer.

Check our out Implications of ChatGPT to Salesforce developers post.

Summary

ChatGPT can be a big game changer for Salesforce Developer and implementation. Let us know how you are using ChatGpt and any use case you can think about for Salesforce.

Nishchal vashisht

Nishchal vashisht

Nishchal vashisht 3x certified, Developer at cloud certitude

Share this article

29 Comments

  • This is amazing! Are you able to link the full code? The link doesn’t seem to be at the end of the blog.

    • Glad you like this post How to integrate ChatGpt with Salesforce. I will update the link soon

  • Thank you!!

  • This is awesome…! Thank you so much for sharing as I was very interested in how this could be used/leveraged in a Salesforce App. I’ll be referring your article to my companies internal Salesforce community as I run a Salesforce CoE.

    • Glad you like this post. Stay connected we will post more code with some use cases with it. text-davinci-003 API is a game changer

  • Hi Amit thank you for great content can please help to achieve this functionality. Or can you please share the full codes of these functionality.

  • Good one.. We are also trying to integrate the same. Officially they haven’t released an API spec yet right?

  • Hello! This is great, I have a question, I’m a user of sfdc, my company makes us document outbound activities and meetings etc. is there a way to have chatgpt document for me, say make the meeting notes look reasonable based off of passed meetings or job title? Thanks

  • Shah Fahad

  • Hello Amit Sir,

    What Key do we have to pass in this line, What do we have to store in the custom setting as a key?

    request.setHeader(‘Authorization’, ‘Bearer ‘+String.escapeSingleQuotes(key).trim());

    Thank you

  • I think we have to add the API Key That we will receive from Open AI

  • @Lincoln if you can give me a brief detail about your use case I can try a POC.

  • Thanks @nischal! I want to provide profiles in salesforce and then have gpt or whatever document a meeting during a set week. For example: Name: craig c
    Profile title “Linux manager”
    Click on add meeting. Then title it xyz
    Then document post meeting notes as” met with Craig, discussed Linux”
    Then click save. Would be glad to jump on a teams meeting and walk through it! Thanks

  • My apologies @nishchal on incorrect spelling of your name! I took some screenshots of what i’m talking about, wondering where i could paste or send them to? Essentially, would click on Activity, click new event, document the subject, then put in pre meeting notes, and post meeting notes, then click save.

  • Hi

    What is POC on connecting to ChatGPT APIs?

  • I didn’t find the custom setting from the code/config provided by you. Can you guide me

  • I tried integrating it, but I don’t know why I’m not getting any response in the chat, I’m new to salesforce with limited knowledge this blog+github+web articles took me 8 hours to reach here, but at the end I see it’s not working idk where I’m missing it, took help from chatgpt but still failed. Can anyone share if they have successfully integrated it with salesforce.

    • Did you tried to call API from the workbench to test your API first?

  • Can you provide the custom setting configuration? Like how its set-up.

  • @Amit I have tried to call the api from workbench but unfortunately not receiving any response, also getting error at the time of deployment the LWC:

    Error 405 Only POST allowed

    HTTP ERROR 405
    Problem accessing /services/Soap/m/50.0. Reason:
    Only POST allowed


    function bodyOnLoad(){if(window.PreferenceBits){window.PreferenceBits.prototype.csrfToken=”null”;};}function bodyOnBeforeUnload(){}function bodyOnFocus(){}function bodyOnUnload(){}

    Please help me to resolve this issue.

  • Hi This look really good. Can you provide test class in the full code ithub link as well? Thanks again for sharin this.

  • Hi Amit , I implemented the same. currently am showing this as normal LWC and set on the pagelayout of custom object. I want this same as chat agent as you did , could you please assist ?

    Thanks in Advance.

    • Congratulation on your POC. I still need to try for agent chat

Leave a reply

Subscribe for Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 4,092 other subscribers

Our Supporter

RECENT POSTS

Apex Hours

Apex Hours is one stop platform to learn Salesforce skills and technology

Join our Newsletter and get tips and tricks how to explore the salesforce for free!