We can create an AI chatbot in Salesforce using Apex classes & LWC or Fetch API in LWC. In both methods, we use the API key of ChatGPT. ChatGPT is an Artificial Intelligence(AI) chatbot developed by an AI research agency, OpenAI. We can use ChatGPT as a chatbot, virtual assistant, language translator, content generator, etc. In this blog, we use Fetch API in LWC to create the chatbot.
Fetch API is a JavaScript method that provides a way to make HTTP requests to the server and handle responses using Promises. It provides a more effortless and alternative approach to generating network requests as compared to the older XMLHttpRequest (XHR). The following steps will lead to creating a Chatbot using Salesforce.
Create a CSP Trusted Site for the AI Chatbot in Salesforce
1. Firstly, log in to your Salesforce Org.
2. Then, click the gear icon from the top-right corner and select “Setup” for navigating to the setup page.
3. Now, type “CSP” in the Quick Find box and then, select “CSP Trusted Sites” from the result. This page displays a list of CSP Trusted Sites that are already registered.
4. Then, click the “New Trusted Site” button to create a new Content Security Policy(CSP) trusted site.
5. Here, enter a name in the “Trusted Site Name” field and enter https://api.openai.com in the “Trusted Site URL” field.
6. Now, check all the checkboxes in the “CSP Directives” section and then Save it.
Create a new API Key for the AI Chatbot in Salesforce
1. Log in to https://platform.openai.com/ using your ChatGPT account credentials.
2. Now, click on the profile icon from the top-right corner of the page and select “View API Keys” from the dropdown. Then click the “+ Create new secret key” button to create a new API key for ChatGPT.
3. Thereafter, provide a name to the API key and click the “Create secret key” button. Immediately, It will generate an API key for you.
4. Further, copy the generated API key from the dialog box and click the “Done” button.
Note: An API key of ChatGPT can only be seen and copied at the time of creation. So, copy it after the creation and put it somewhere for later use.
Create a Salesforce DX Project and an LWC component for the Chatbot
To create a Salesforce DX project, you must set up a Salesforce DX environment on your device. This consists of installing Salesforce CLI, Visual Studio Code, and Salesforce Extension Pack. If you have not set up the Salesforce DX environment then, you can follow this blog to setup it up:
1. First, open the Visual Studio Code on your device.
2. Now, create a project following the path, View > Command Palette, and then select SFDX: Create Project. Select “Standard” as a project template, provide a name to the project, and then locate it on the device.
3. Then, authorize the project with your Salesforce ORG following the path, View > Command Palette > SFDX: Authorize an Org, select Project Default, and give an Org Alias. It will redirect to the Salesforce login page.
4. Here, log in with your Salesforce Org credentials.
5. Now, from View > Command Palette, select SFDX: Create Lightning Web Component. Then, provide a name to the component and press “Enter” when it asks where to save the component.
6. Thereafter, replace the default code of the Html file with the following code:
<template>
<lightning-card title="LWC Chatbot with Fetch API" icon-name="standard:live_chat">
<div class="slds-box slds-box_xx-small slds-var-m-horizontal_xx-small slds-theme_default">
<div class="slds-m-bottom_none slds-chat chat">
<ul class="slds-chat-list">
<template for:each={conversation} for:item="message">
<li key={message.id} class="slds-chat-listitem slds-var-m-bottom_small">
<div class={message.containerClass}>
<div class="slds-chat-message__text slds-text-align_left">
<template if:true={message.isBot}>
<span class="slds-avatar slds-avatar_circle slds-var-m-left_xx-small slds-align-middle">
<abbr class="slds-avatar__initials slds-icon-standard-strategy" title="ChatGPT">AI</abbr>
</span>
<span class={message.textClass}>{message.text}</span>
</template>
<template if:false={message.isBot}>
<span class="slds-avatar slds-avatar_circle slds-var-m-left_xx-small slds-align-middle">
<abbr class="slds-avatar__initials slds-icon-custom-custom101" title="User">RM</abbr>
</span>
<span class={message.textClass}>{message.text}</span>
</template>
</div>
</div>
</li>
</template>
</ul>
<template if:true={isLoading}>
<lightning-spinner variant="brand" class="my-spinner" alternative-text="Loading" size="medium">
</lightning-spinner>
</template>
</div>
<div class="slds-grid slds-gutters slds-var-p-horizontal_xx-small">
<div class="slds-col slds-size_3-of-4">
<lightning-input type="text" label="Type your message" value={messageInput} onchange={handleChange} onkeyup={handleKeyUp}></lightning-input>
</div>
<div class="slds-col slds-size_1-of-4 slds-align-bottom slds-var-p-top_medium">
<lightning-button label="Send" onclick={handleSendMessage} variant="brand"></lightning-button>
</div>
</div>
</div>
</lightning-card>
</template>
7. Again, replace the default code of the JavaScript file with the below code. Don’t forget to replace COMPONENT_NAME with your component name(make the first letter capital) while exporting the default class in the code. Also, replace YOUR_API_KEY with the API key of ChatGPT that you generated earlier.
import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class COMPONENT_NAME extends LightningElement {
@track conversation = [];
@track messageInput = '';
@track isLoading = false;
handleChange(event) {
this.messageInput = event.target.value;
}
handleKeyUp(event) {
if (event.keyCode === 13) {
this.handleSendMessage();
}
}
async handleSendMessage() {
this.isLoading = true;
this.template.querySelector(".slds-chat").classList.add('parent');
const userMessage = {
id: 'user-' + this.conversation.length,
role: 'user',
text: this.messageInput,
containerClass: 'slds-chat-message slds-chat-message__text_outbound user-message',
textClass: 'slds-chat-message__text slds-chat-message__text_outbound',
isBot: false
};
this.conversation = [...this.conversation, userMessage];
this.messageInput = '';
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY' // Replace YOUR_API_KEY with your actual API key
},
body: JSON.stringify({
messages: [{
role: 'user',
content: this.conversation[this.conversation.length - 1]?.text
}],
model: 'gpt-3.5-turbo'
})
});
if (response.ok) {
const responseBody = await response.json();
this.isLoading = false;
if (responseBody && responseBody.choices && responseBody.choices.length > 0) {
const assistantMessage = {
id: 'assistant-' + this.conversation.length,
role: 'assistant',
text: responseBody.choices[0].message.content,
containerClass: 'slds-chat-message slds-chat-message__text_inbound',
textClass: 'slds-chat-message__text slds-chat-message__text_inbound',
isBot: true
};
this.conversation = [...this.conversation, assistantMessage];
} else {
this.dispatchEvent(new ShowToastEvent({
title: 'ERROR!!!',
message: 'Error generating ChatGPT response: Empty response',
variant: 'error'
}))
}
} else {
const errorBody = await response.json();
throw new Error('Error: ' + response.status + ' ' + response.statusText + ' - ' + errorBody.error.message);
}
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'ERROR!!!',
message: error.message,
variant: 'error'
}))
this.isLoading = false;
}
}
}
8. Also, replace the code of the XML file with the following code:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
9. Now, save these 3 files and right-click on the lwc under force-app\main\default and select SFDX: Deploy Source to Org.
Place the component in an App Page
1. Now in your Salesforce Org, navigate to a Salesforce app through App Launcher(located at the top-left corner of the page).
2. Then, click the gear icon and select “Edit Page” to edit the page in the app builder.
3. After, drag and drop the chatbot component inside the canvas in the middle. Then click the “Save” button at the top-right corner. Then, a dialog box will appear to activate the component.
4. Click the Activate button and then click “Assign as Org Default” and Save it.
5. Thereafter, click the left arrow at the top-left corner of the app builder to exit from it. Now, your AI Chatbot is ready to use.
Creating an AI Chatbot is a part of ChatGPT and Salesforce Integration. You can also read our other blog on ChatGPT and Salesforce Integration with Zapier which summarizes the Lead record and put the summary in the description field of the respective Lead record. You can learn about using Webhook, ChatGPT, and Salesforce in Zapier.
Please contact us at manish@bay20.com or call us at +91-8800519180 for any support related to Salesforce. You can also visit the Salesforce development page to check the services we offer.