Skip to content

Instantly share code, notes, and snippets.

@amitastreait
Created May 13, 2023 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitastreait/abeb230de243394918b37f27530fcfed to your computer and use it in GitHub Desktop.
Save amitastreait/abeb230de243394918b37f27530fcfed to your computer and use it in GitHub Desktop.
How to integrate CHAT GPT with Salesforce
global without sharing class ChatGPTClass {
// ChatGPTClass.generateResponse('Hello');
@AuraEnabled
public static String generateResponseFromGPT(String queryText){
try {
String content = generateResponse(queryText);
return content;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
public static String generateResponse(String queryText){
HttpRequest httpReq = new HttpRequest();
httpReq.setEndpoint('https://api.openai.com/v1/chat/completions');
httpReq.setMethod('POST');
httpReq.setHeader('Content-Type','application/json');
httpReq.setHeader('Authorization', 'Bearer <YOUR_API_KEY_HERE>');
String body = '{'+
' "model": "gpt-3.5-turbo",'+
' "messages": ['+
' {'+
' "role": "user",'+
' "content": "'+queryText+'"'+
' }'+
' ]'+
'}';
httpReq.setBody(body);
Http http = new Http();
HttpResponse httpResponse = http.send(httpReq);
String content = '';
if(httpResponse.getStatusCode() == 200){
System.debug(httpResponse.getBody());
ChatWrapper wrapper = (ChatWrapper)System.JSON.deserialize(httpResponse.getBody(), ChatWrapper.class);
List<ChatGPTClass.Choices> choices = wrapper.choices;
if(choices != null && choices.size() > 0){
ChatGPTClass.Choices choice = choices.get(0);
if(choice.message != null){
content = choice.message.content;
System.debug(content);
}
}
}else{
System.debug('Error Occured !');
System.debug(httpResponse.getBody());
}
return content;
}
global class ChatWrapper{
public String id;
public Choices[] choices;
}
global class Choices {
public Message message;
public String finish_reason;
public Integer index;
}
global class Message {
public String role;
public String content; //there! How can I assist you today?
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment