
Using the HTTP Callout action in Salesforce Flow, it is possible to make calls to external web services without writing a single line of code. This powerful capability opens up a world of opportunities for integrating Salesforce with external systems and services. For instance, it is possible to integrate ChatGPT with Salesforce to streamline processes and enhance customer interactions.
In this post, we will explore how to harness the potential of the HTTP Callout action to seamlessly integrate ChatGPT with Salesforce. This integration can revolutionize the way you engage with your customers and manage data within your Salesforce environment.
What is ChatGPT?
ChatGPT is an AI chatbot using natural language processing to create human-like conversations and various content like articles and emails. It operates as generative AI, users input prompts to get AI-generated text. Similar to customer service chatbots, users can ask questions and get response from ChatGPT. It undergoes training with reinforcement learning, which uses human feedback to improve future responses.
Integrating ChatGPT into Salesforce can be crucial for enhancing customer interactions and streamlining processes. Using ChatGPT in Salesforce, it is possible to provide instant responses to customer inquiries and generate personalized content. This can ultimately boost efficiency and customer satisfaction within the Salesforce ecosystem.
Let's see how to use the HTTP Callout action in order to integrate ChatGPT with Salesforce.
Steps Before Building the Action
There are a few steps before building the HTTP Callout action in flow.
1- The first step is to add an external credential. Search for named credentials in setup and then create a new external credential.

2- In order to integrate with Salesforce, you have to create an API key in OpenAI. After logging in to OpenAI, click to view API keys and then create a new secret key.

3- Copy the API key that you created and create a custom header related to the external credential. Name should be "Authorization" and paste the API key after writing "Bearer " into the value.

4- Create a new principal related to the external credential. This step is important for giving permissions through profile or permission sets.

5- Create a new named credential and choose the external service that you created in the previous step.

6- In order to give permission to specific users, create a new permission set. Then, give access to the external credential principal that you created.

Now, you can create the HTTP Callout action from flow.
Creating the HTTP Callout Action
It is possible to create an HTTP Callout action from any flow type that supports the action element. Let's create the HTTP Callout action from a screen flow.
1- Add an action element and click the "Create HTTP Callout" button. Give a name to the external service and choose the named credential that you created before.

2- Give a name to the invocable action and choose POST as the method. We want to use ChatGPT's chat completions API. Therefore, enter /v1/chat/completions as the URL path.

3- Next, you have to provide a sample request and a sample response.
Use this as the sample request.
{
"max_tokens": 1,
"temperature": 2.5,
"messages": [
{
"role": "sample string",
"content": "sample string"
}],
"model": "sample string"
}
Use this as the sample response.
{
"created": 1,
"usage": {
"completion_tokens": 1,
"prompt_tokens": 1,
"total_tokens": 1
},
"model": "sample string",
"id": "sample string",
"choices": [{
"finish_reason": "sample string",
"index": 1,
"message": {
"role": "sample string",
"content": "sample string"
},
"logprobs": true
}],
"system_fingerprint": 1,
"object": "sample string"
}

After this step, you have an invocable action that you can use to integrate ChatGPT with Salesforce.
Build a Flow to Integrate ChatGPT with Salesforce
Let's build a simple screen flow to integrate ChatGPT with Salesforce.
1- Add a screen element with a text input field, so that the user can type in their question.

2- In order to use the invocable action that you created, you have to assign values to the Apex-defined variable. This will be the body of your request. In chat completions API, the body itself has a collection in it. Therefore, we will use an Assignment element to add the message (question) to a collection, then add it to the body.
Create a new single Apex-defined variable for the message and then use an Assignment element to assign the question.


Pay attention that BodyMessages is also an Apex-defined variable, but this time it is a collection.
3- Create an Apex-defined variable for the request body. Then, use an Assignment element to assign the request body.


As you can see, we are assigning the BodyMessage (from the previous step) to the body.
4- Add an Action element and choose the invocable action that you created. Then choose the Apex-defined variable that you assigned as the request body.

5- This action's response has a collection called "Choices". Add an Assignment element and assign the "Choices" collection to an Apex-defined collection variable.


6- Since the response is a collection, you have to use Loop and Assignment elements in order to extract the real response that you need.

Create a new Apex-defined variable (single) for the Choice value.

Then, use an Assignment element to assign the current item from the loop to the ChoicefromOutput variable.

6- At the end of the loop, answer for your question will be stored in {!ChoicefromOutput.message.content}.
Create a formula to remove some tags. Then, display the result of the formula using a screen element.


At the end, your flow should look like this.

Demo
Here is how it works. As you can see, flow displays ChatGPT's answer for the user's question.

Improvements
In this post, we saw how to use flow to integrate ChatGPT with Salesforce. Besides giving users a screen to ask questions, it is possible to use this integration in many areas. For instance, it is possible to build a flow that helps users solve cases.

On the other hand, you can build a record-triggered flow to automate the process as well.
To sum up, integrating ChatGPT with Salesforce empowers businesses to elevate customer engagement. It automates tasks and enhances overall operational efficiency. Moreover, it fosters growth and improved customer satisfaction.
Very nice and detailed article! I just have one question - isn't it possible to skip the collection loop and directly assign "Choice.Text" to a variable? I believe that you don't use anything else from the response only the text, so if it is possible to skip the loop - it should work faster at the end? 🙂
Hi Nikola,
The output of this callout is a collection, that's why I had to use a loop.
Hi Yumi,
Great how-to, so much appreciated, exactly what I'm looking for to implement in my Org.
I followed every step including periods and commas, but when it makes the callout, I'm only getting this output:
Outputs
defaultExc ({ "message": "Welcome to the OpenAI API! Documentation is available at https://platform.openai.com/docs/api-reference" })
responseCode (421)
Here's what it shows in debug:
Inputs
body = {!Body} (HTTPCallout_ChatGPT_IN_body : { "temperature_set" : true, "temperature" : 0.7, "model_set" : true, "model" : "gpt-4", "messages_set" : true, "messages" : [ { "role_set" : true, "role" : "user", "content_set" : true, "content" : "Occupation: \\nYou only will return a numeric value (the score).\\nYou will help to categorize the provided Occupation into one of these categories to return the Score of the provided Occupation, if you can't categorize it, you will return 2.5\\n\\n\\nHigh Expected Salary Industries (Score: 5)\\nPharmaceuticals\\nBiotechnology\\nOil and Gas Exploration\\nInvestment Banking\\nSoftware Development\\nAerospace and Defense\\nCorporate Law\\nConsulting (Management, Technical)\\nMedical Equipment Manufacturing\\nSemiconductor Manufacturing\\nLuxury Goods\\nCommercial Real Estate\\nFinancial Services\\nTelecommunications\\nAdvanced Electronics\\nIT Management\\nArtificial Intelligence and Robotics\\nNuclear Energy\\nEnvironmental Engineering\\nCorporate Executive Management\\n\\nAbove Average Expected Salary Industries (Score: 4)\\nGeneral Healthcare\\nConstruction Engineering\\nAutomotive Manufacturing\\nInformation Technology Services\\nCommercial Banking\\nInsurance\\nReal Estate Development\\nMarketing and Advertising\\nSecondary Education\\nLogistics and Transportation\\nChemical Manufacturing\\nElectrical Engineering\\nRetail Management\\nHospitality Management\\nGraphic Design and Multimedia\\nHR and Recruitment Services\\nInternational Trade\\nFood and Beverage Manufacturing\\nAgricultural Technology\\nRenewable Energy\\n\\nAverage Expected Salary Industries (Score: 3)\\nRetail\\nPrimary Education\\nGeneral Manufacturing\\nHealthcare Support\\nLocal Government\\nAgriculture\\nHospitality Services\\nCustomer Service\\nAdministrative Services\\nLegal Services (non-corporate)\\nSocial Work\\nPublic Safety (Police, Firefighting)\\nNon-profit Organizations\\nFood Service\\nResidential Real Estate\\nSmall Business Management\\nAutomotive Repair\\nLocal Media (Newspapers, Radio)\\nArts (Theater, Museums)\\nEnvironmental Conservation\\n\\nBelow Average Expected Salary Industries (Score: 2)\\nRetail Sales\\nPersonal Care Services\\nChildcare Services\\nCleaning Services\\nCall Centers\\nFast Food and Quick Service Restaurants\\nLandscaping and Gardening\\nHome Health Care\\nElderly Care Services\\nBasic Administrative Support\\nCommunity Services\\nSecurity Services\\nWarehouse Operations\\nTextile Manufacturing\\nBasic Construction\\nData Entry and Transcription\\nDelivery Services\\nBasic Educational Support (e.g., Teaching Assistants)\\nEntry-Level Government Services\\nRecreation Services (e.g., Fitness Centers)\\n\\nLow Expected Salary Industries (Score: 1)\\nFast Food Restaurants\\nSmall-scale Retail (e.g., Convenience Stores)\\nBasic Housekeeping Services\\nLaundry Services\\nEntry-Level Agricultural Work\\nBasic Hospitality Services (e.g., Motels)\\nStreet Vendors and Informal Markets\\nBasic Landscaping Services\\nEntry-Level Warehouse Staff\\nSeasonal Labor (e.g., Harvesting)\\nSmall-scale Catering Services\\nBasic Janitorial Services\\nCashiering in Small Retail Outlets\\nBabysitting and Nanny Services\\nPet Care Services\\nEntry-Level Clerical Work\\nCar Wash Services\\nTelemarketing\\nDoor-to-door Sales\\nEntry-Level Food Delivery Services" } ], "maxx5ftokens_set" : true, "maxx5ftokens" : 50 })
Outputs
defaultExc ({ "message": "Welcome to the OpenAI API! Documentation is available at https://platform.openai.com/docs/api-reference" })
responseCode (421)
Hi,
What is the URL in your named credential? It should be https://api.openai.com
Did you add a URL path in your invocable action? It should be /v1/chat/completions
Silly me! I thought I did, but in the last attempt forgot to include it, thank you so much!
Blessings!
Hi Yumi,
Hope you're doing well! First I wanted to say thank you for your detailed article.
I was able to get this POC to work in my env 2 weeks back. And today I'm getting an error when I tried to trigger the flow.
Error: Error Occurred: Unable to map response for output parameter 2XX of invocable action OpenAI.ChatCompletions. Received response: { "id": "chatcmpl-8uMCfnhY3QKGt9aKWBcFEoflZocNn", "object": "chat.completion", "created": 1708442409, "model": "gpt-3.5-turbo-0125", "choices": [ { "index": 0, "message": { "role": "assistant", "content":
I want to see if you're getting the same error. Could this be json response body issue?
Hi,
Can you try with model gpt-4 ?
Hi, did you find a solution? I am getting the same error
Great content. What kind of license do we need here? Do we need a ChatGPT pay account?
Right, you need a paid ChatGPT account/key.
how do push files from Salesforce to OpenAI?