Skip to main content

Integrate Salesforce to ChatGPT

Connecting ChatGPT with Salesforce

You need to follow below steps in order to connect ChatGPT to salesforce.

                

1.           Create and configure your OpenAI account.

Go to https://openai.com/ and setup your account. Click on Log in and it will take you to a page where you can sign up using various methods like google or your email.

Once you have logged in into OpenAI, you will see below page. Please select API.

Optionally, if you do not have idea or need knowledge on how ChatGPT works, please go through the documentations and references.

2.           Get OpenAI API keys to integrate.

Click on API Keys to get your personal API key (Note: The professional/industrial use will require more licensing. Please refer to OpenAI policies).

Click on Create new secret key to generate a key for yourself. Give a name to your key and it will generate a new key using which we will be able to connect to ChatGPT.

Once you have created the key, it will look like below.

Make sure the permission is selected as All (default).

3.           Setup Salesforce to be able to connect to ChatGPT.

Go to your Salesforce Org and go to Setup, then go to Custom Settings. Create a new Custom Setting object. You can label it as you wish we are labelling it as OpenAiKey which will in turn become our object API name as OpenAiKey__c.

Add 2 custom fields as displayed below.


Once you have created the Custom Setting create fields, click on Manage to create a new record.

Enter values –

Location = default (your org company name)

End point = https://api.openai.com/v1/completions

API Key = The API key you generated in Step 2

Your Salesforce setup is almost done, just one step left.

Go to Remote Site Setting. It is important for allowing connection to the OpenAI end point.

Click on New Remote Site and create as below. https://api.openai.com

Hurray! Our Salesforce setup is done

4.          Write custom code to callout to ChatGPT and get response.

Go to Developer Console and create a new class (Name: AI_ChatGPT_BASIC). Paste below code. The code has comments added for your better understanding.

/*

@description       : ChatGPt hitting class which will search your query.

@author            : Sumit Kumar

*/

 

public with sharing class AI_ChatGPT_BASIC {

    static String orgId = UserInfo.getOrganizationId();

    private static String CHAT_GPT_KEY = OpenAiKey__c.getValues(orgId).API_Key__c; //Custom Setting

    private static final String ENDPOINT = OpenAiKey__c.getValues(orgId).End_Point__c;

   

    //@method   : getQueryData

    //@param    : searchString

    //@description  : Below method is used in Salesforce+Chat GPT integration LWC as Controller to make callout

    //                to Chat GPT and return response/error from this method

    @AuraEnabled

    public static String getQueryData(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.setMethod('POST');

            request.setHeader('Authorization', 'Bearer '+String.escapeSingleQuotes(CHAT_GPT_KEY).trim());

            //Setting timeout to max 120 second to get whole response from Chat GPT Open API

            request.setTimeout(120000);

            request.setHeader('Content-Type', 'application/json;charset=UTF-8');

            // Set the body as a JSON object

            request.setBody(reqBody);

            HttpResponse response = http.send(request);

            // Parse the JSON response

            if(response.getStatusCode() != 200 || response.getStatusCode() != 201) {

                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());

        }

    }

}

 

Now your class and method are ready to be used either in LWC or ScreenFlows. The parameter searchString is the string which will hold your query.

 

Hope it helps. Feel free to comment your queries or suggestions. I will definitely try to help.

Comments

Post a Comment

Please comment your thoughts. It helps.

Popular posts from this blog

Salesforce - Enable guest user on your digital experience site or community

Learnings -  👉 How guest user profiles work in Salesforce 👉 Configuring a guest user profile 👉Managing access and best practices Guest users in Salesforce Communities/Sites  Guest user profiles are used for controlling the public or unauthenticated access to your org's data i.e. it controls the access you give to the users who have not logged into your community.  Guest users can always see login and login error pages in your site.  Every time a portal or site is created in your Salesforce org, a Guest User Profile is automatically created at the backend. These auto-created profiles are very restrictive and do not allow any data or object visibility to guest users. Each community or site has a guest user associated with it. If you have 10 communities in your org, you will have 10 different guest users. Configuring guest user profiles in Salesforce Guest user profiles are not visible in the Setup>Profile section. Follow the below steps to go to the Guest user pr...

Salesforce LWC - Uncommon and Difficult, Tough, Tricky Interview Questions Answers | LWC interview: Advance Level

  How is LWC different from the Lightning Aura framework? Which is better to use? Aura components are upgraded to LWC to better utilize modern JavaScript and Web Stack. It was not possible for Salesforce to come with LWC before as the Web Stack would not support it. So, it is an upgraded version of the Aura component, hence it is always better in every way. However, when you develop Lightning web components, you also may need to use Aura, because LWC doesn’t yet support everything that Aura does. Always choose Lightning Web Components unless you need a feature that isn’t supported. Lightning web components are custom HTML elements built using HTML and modern JavaScript. Lightning Web Components uses core Web Components standards and runs natively in browsers, therefore, Lightning Web Components is lightweight and delivers exceptional performance. Aura components can be integrated within LWC, but it is not the same vice versa. Utilizing modern JavaScript makes it easier to be adopte...