In the world of software development, chatbots and conversational interfaces have become increasingly popular for providing efficient and engaging user experiences. Leveraging AI-powered chatbots is a valuable addition to any application, and OpenAI's GPT-3-based model, ChatGPT, is at the forefront of this revolution. In this blog post, we'll explore how to integrate ChatGPT with a Spring Boot application, creating a powerful conversational agent.
Create a new spring boot project using your preferred IDE or Spring Initializer
Add the necessary dependencies for Spring Web in the pom.xml file
Create a config class with the bean which will be returning RestTemplate
User the proper annotations required
package com.demo.chatgptintegration.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author viveksoni
*/
@Configuration
public class ServiceConfig {
/**
* we are using RestTemplate to process OpenAI's API
*/
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Create a service class which will be accepting the string passed by the user
package com.demo.chatgptintegration.service;
import com.demo.chatgptintegration.dto.GptRequest;
import com.demo.chatgptintegration.dto.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
/**
* @author viveksoni
*/
@Service
public class OpenAIService {
@Autowired
private RestTemplate restTemplate;
@Value("${openai.api.key}")
private String apiKey;
private String url = "https://api.openai.com/v1/chat/completions";
private String modelId = "gpt-3.5-turbo";
public String openAIServiceCall(String userInput) {
var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer " + apiKey);
var requestBody = "{\"model\": \"" + modelId + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + userInput + "\"}]}";
HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
var response = restTemplate.postForObject(url, request, String.class);
return response;
}
}
Generate API key from the OpenAI portal
visit https://platform.openai.com/ Login or Sign up then go to View API keys from the menu

create new secret key

Choose Model Id from the OpenAI portal

Create a new class called ChatController with the necessary annotations
Implement an endpoint to receive chat messages as a GET request
Use RestTemplate to make a POST request to the ChatGPT API endpoint
Handle the API response and return it to the client
package com.demo.chatgptintegration.controller;
import com.demo.chatgptintegration.service.OpenAIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author viveksoni
*/
@RestController
public class ChatController {
@Autowired
OpenAIService service;
@GetMapping("/chat")
public String callingAI(@RequestParam("userInput") String userInput) {
String response = service.openAIServiceCall(userInput);
return response;
}
}
http://localhost:9090/chat?userInput=tell%20me%20a%20joke


In this simple guide, we've explored the seamless integration of ChatGPT, OpenAI's powerful conversational AI model, into Spring Boot applications. The fusion of ChatGPT's natural language processing capabilities with Spring Boot's robust framework empowers developers to create sophisticated chatbots, virtual assistants, and conversational interfaces with ease.
The integration of ChatGPT with Spring Boot opens up a world of possibilities for engaging, interactive, and intelligent applications. Whether you're building customer support bots, creative writing assistants, or anything in between, ChatGPT integration in Spring Boot is a powerful tool in your development arsenal. We hope this simple guide has equipped you with the knowledge and confidence to embark on this exciting journey of creating conversational experiences that leave a lasting impact on your users.