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 we will try to get you familiar with it and use case for Chat GPT Integration in Salesforce. Join us to learn about Salesforce Integration with ChatGPT.

What is Chat GPT?

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.

YouTube video

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.

YouTube video

Let see how Salesforce Integration with ChatGPT. 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.

GPT-4 and Salesforce Potential features

Check out GPT-4 and Salesforce Potential features and scenarios.

  1. Natural Language Processing (NLP) and Chatbots
  2. Predictive Sales
  3. Personalized Communication
  4. Predictive Sales Trends
  5. Conversation Analysis

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
5x certified, Developer at Yoti

Articles: 8

41 Comments

  1. 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

  2. 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.

  3. 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

  4. 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

  5. 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

  6. 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.

  7. 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.

  8. @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.

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

  10. 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.

  11. Great post, thanks!
    I’ve been very impressed with the AI extension for VS Code called CoPilot. This one automatically generates code based on your //comments. And it even suggests what the next comment or step might be. Very seamless integration into my dev workflow.

  12. I can not find the OpenAiKey_c custom settings, where you defined the key. Can you please share that as well? Thank you very much!

  13. Thank you for the code Amit. Could you elaborate this step “3 : Hit OpenAI endpoints by using a secret Key at server side.your request will look like this.”

  14. Hi Amit, great video and sharing the code. Much appreciated. If you can, please add another demo using LangChain as it remembers the session history.

Leave a Reply

Your email address will not be published. Required fields are marked *