Salesforce Integration with ChatGPT [2024]

Salesforce Integration with ChatGPT (Kizzy Consulting - Top Salesforce Partner)

Hey Guys, today we are discussing Salesforce Integration with ChatGPT (which is a product of openAI). Everyone is aware of ChatGPT which thrived and gained 1 million users in just 5 days. To understand if the whole discussions going on in the social circles were a fad or a real trend, we worked on integrating Chat GPT with Salesforce. Join the boat of learning in this article to know more about Salesforce integration with ChatGPT.

What is OpenAI?

OpenAI is an AI research lab and company that develops and supports safe and effective AI technologies. Founded in 2015, OpenAI is known for creating advanced language models such as GPT-3 that can generate human-like responses to text. OpenAI’s main goal is to improve artificial intelligence while ensuring fair and responsible use. 

What is ChatGPT?

ChatGPT is a high-level language model developed by OpenAI. It belongs to the GPT (Generative Pre-trained Transformer) family, which uses deep learning techniques to generate human-like responses from instructions. ChatGPT, like Supervised Machine Learning, is trained on a wide variety of data, making it easy to understand and generate similar responses and related content. It can engage in interactive conversations, provide information, answer questions, and even see behavior. ChatGPT’s ability to transform many applications, including customer support, content creation, and virtual assistants, makes it a valuable tool for improving human-machine interaction.

Benefits of integrating ChatGPT with Salesforce

Integrating ChatGPT, a state-of-the-art language model can have multiple benefits, some of which are listed below to lure our developer friends into trying this new functionality out.

  1. Better Customer Interaction: Salesforce can transform customer interactions and support within the platform more efficiently with the help of ChatGPT. With ChatGPT’s powerful messaging capabilities, businesses can provide more personalized and effective customer service. With ChatGPT’s ability to understand and respond to natural language, businesses can improve customer support experience and efficiency in the Salesforce ecosystem.
  2. Helping hand inside the organization: By seamlessly integrating ChatGPT into Salesforce, companies can provide their employees with an intelligent virtual assistant that can handle a variety of customer questions and support requests. This integration results in answers to many questions, saves agent time to do more complex tasks, and improves overall customer satisfaction.

ChatGPT Integration in Salesforce:

  1. Set the HTTP method to POST.
  2. Specify the URI as ““.
  3. In the request body (Raw), provide the necessary information in JSON format:
    1. Set the “model” value as “gpt-3.5-turbo”.
    2. Include the user’s message within the “messages” array, with the role as “user” and the content as the desired query.
  4. Configure the authorization type as Bearer Token.
  5. Enter the access token (“sk-xxxxxxxxxxxxxxxxxxxxx”) provided by OpenAI.
  6. Send the request to the API endpoint.
  7. Retrieve the response, which will contain the generated reply from the ChatGPT model.

By following these steps, We can effectively use ChatGPT via POSTMAN, leveraging its conversational abilities for various applications such as customer support, virtual assistance, and more.

Salesforce Integration with ChatGPT (Kizzy Consulting - Top Salesforce Partner)


Salesforce Integration with ChatGPT (Kizzy Consulting - Top Salesforce Partner)

To discover the best practices for seamless Salesforce integration and unlock the full potential of your business processes, check out our comprehensive guide on Salesforce integration best practices.

ChatGPT Integration in Salesforce using APEX:

  1. Create an LWC component that will provide a chat window-like interface.



  <!–Lightning card for OpenAI–>

  <lightning-card title=“OpenAI”>

    <lightning-spinner alternative-text=“Loading…” variant=“brand” if:true={IsSpinner}>


    <div class=“slds-p-around–small”>


      <lightning-textarea name=“input1” value={question} onchange={handleChange}></lightning-textarea>


    <div class=“slds-align_absolute-center”>

      <lightning-button variant=“brand” label=“Ask??” title=“Primary action” onclick={handleClick}







import { LightningElement, track } from ‘lwc’;

//Importing the Apex method to use in Js Controller

import getOpenAIResponse from ‘@salesforce/apex/IntegrateChatGPTWithSalesforce.getOpenAIResponse’;

export default class ChatGPTController extends LightningElement {

    @track question = ‘Hello!’;

    @track IsSpinner = false;

    @track lstData = [];


    // this method will be used to store the Input Value in the Variable

    handleChange(event) {

        this.question =;



    //This method is used to call the Apex to send the request to the Open-AI

    handleClick() {

        // to start the spinner

        this.IsSpinner = true;

        getOpenAIResponse({ messageBody: this.question })

            .then(result => {

                if (result != null) {

                    //update the data to the apex response

           = result;

                    //to stop the spinner 

                    this.IsSpinner = false;






Hit OpenAI endpoints by using a secret Key

//this class is used to Handle the Event from the ChatGPTController.

public class IntegrateChatGPTWithSalesforce {


    public static String getOpenAIResponse(String messageBody) {

        // to get the endpoint url and Access Token From Custom Meta Data

        IntegrateChatGPTWithSalesforce__mdt newIntegrateChatGPTWithSalesforce = [SELECT URL__c FROM IntegrateChatGPTWithSalesforce__mdt WHERE Label = ‘endPoint’ ];

        String endPointUrl = newIntegrateChatGPTWithSalesforce.URL__c;

        String accessToken = getAccessToken(); // Retrieve access token securely


        Http http = new Http();

        HttpRequest request = new HttpRequest();


        request.setHeader(‘Content-Type’, ‘application/json’);

        request.setHeader(‘Accept’, ‘application/json’);

        request.setHeader(‘Authorization’, ‘Bearer ‘ + accessToken);



        Map<String, Object> requestBody = new Map<String, Object>();

        // set this body to get the Response for the Question to Open AI  

        requestBody.put(‘model’, ‘gpt-3.5-turbo’);


        List<Map<String, Object>> messages = new List<Map<String, Object>>();

        Map<String, Object> message = new Map<String, Object>();

        message.put(‘role’, ‘user’);

        //This is the Question to the Open Ai

        message.put(‘content’, messageBody);


        requestBody.put(‘messages’, messages);


        String requestBodyJson = JSON.serialize(requestBody);



        HttpResponse response;

        try {

            response = http.send(request);

            if (response.getStatusCode() == 200) {

                FromJSON data = (FromJSON) JSON.deserialize(response.getBody(), FromJSON.class);

                if (data.choices != null && data.choices.size() > 0) {

                    String content = data.choices[0].message.content;

                    system.debug(‘content: ‘ + content);

                    return content;

                } else {

                    return null;


            } else {

                return null;


        } catch (Exception ex) {

            System.debug(‘Exception: ‘ + ex.getMessage());

            throw ex;




    // Method to retrieve access token securely

    private static String getAccessToken() {

        IntegrateChatGPTWithSalesforce__mdt newIntegrateChatGPTWithSalesforce = [SELECT Access_token__c

                                                                                 FROM IntegrateChatGPTWithSalesforce__mdt 

                                                                                 WHERE Label = ‘endPoint’ ];

        return newIntegrateChatGPTWithSalesforce.Access_token__c;


    //Wrapper to handle the Api response from the Open Ai Tool 

    public class FromJSON {

        public String id;

        public Integer created;

        public String model;

        public List<ClsChoices> choices;

        public ClsUsage usage;



    public class ClsChoices {

        public Integer index;

        public ClsMessage message;

        public String finish_reason;



    public class ClsMessage {

        public String role;

        public String content;



    public class ClsUsage {

        public Integer prompt_tokens;

        public Integer completion_tokens;

        public Integer total_tokens;



Kizzy Consulting

Kizzy Consulting is a Salesforce Consulting Partner and has successfully implemented 100+ Salesforce projects for 100+ clients across sectors like Financial Services, Insurance, Retail, Sales, Manufacturing, Real estate, Logistics, and Healthcare in countries like the US, Europe, and Australia. Get a free consultation now by emailing us at [email protected] or Contact us.

Leave a Reply

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

Skip to content