Integrating ChatGPT with a Spring Boot Application

ChatGPT is a powerful language model developed by OpenAI that can generate human-like responses in conversational scenarios. In this blog post, we will explore how to integrate ChatGPT into a Spring Boot application, allowing us to build intelligent chatbots or virtual assistants.

Setting Up the Project

To get started, create a new Spring Boot project using your preferred IDE. Make sure to include the necessary dependencies for web and RESTful API communication. You can use Maven or Gradle to manage your project's dependencies.

Configuring the ChatBot

In the project, create a configuration class named ChatBotConfig. This class will provide a RestTemplate bean configured with the required headers for API communication. The OpenAI API key, which grants access to ChatGPT, will be injected via the @Value annotation.

Creating the Chat Controller

Next, we'll create a controller class named ChatBotController that handles the chat requests. It will have a method annotated with @GetMapping to handle GET requests and accept a query parameter named prompt, which represents the user's message.

This controller class uses the injected RestTemplate bean to make a POST request to the ChatGPT API endpoint, passing the user's message as the request body. The API response is mapped to the ChatGptResponse object, from which we extract the generated chat message

Defining Request and Response DTOs

To facilitate communication with the ChatGPT API, we need to define data transfer objects (DTOs) for the request and response payloads. These DTOs will be used to serialize and deserialize JSON data.

The ChatGptRequest class represents the request payload and contains the model name and a list of messages, including the user's message.

The ChatGptResponse class represents the response payload and contains a list of choices, each containing an index and a message.

Testing the Chat Endpoint

To test the chat functionality, start the Spring Boot application and send a GET request to the /bot/chat endpoint with the prompt query parameter set to the user's message. The controller will return the generated chat message as the response.

The response will contain the chatbot's reply, providing an interactive conversation experience.

Conclusion

In this blog post, we explored how to integrate ChatGPT into a Spring Boot application to build chatbots or virtual assistants. We covered the setup of the project, configuration of the ChatBot, creation of the controller, and definition of request and response DTOs.

Integrating ChatGPT with a Spring Boot Application code example

//Configuration class
@Configuration
public class ChatBotConfig {

    @Value("${openai.api.key}")
    private String openApiKey;

    @Bean
    public RestTemplate getTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add("Authorization", "Bearer " + openApiKey);
            return execution.execute(request, body);
        });
        return restTemplate;
    }
}
//Rest Controller class
@RestController
@RequestMapping("/bot")
public class ChatBotController {

    @Value("${openai.model}")
    private String model;

    @Autowired
    private RestTemplate template;

    @Value("${openai.url}")
    private String apiUrl;

    @GetMapping("/chat")
    public String chat(@RequestParam("prompt") String prompt) {
        ChatGptRequest request = new ChatGptRequest(model, prompt);
        ChatGptResponse chatGptResponse = template.postForObject(apiUrl, request, ChatGptResponse.class);
        return chatGptResponse.getChoices().get(0).getMessage().getContent();
    }
}
//Data transfer classes
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatGptRequest {
    private String model;
    private List<Message> messages;

    public ChatGptRequest(String model, String prompt) {
        this.model = model;
        this.messages = new ArrayList<>();
        this.messages.add(new Message("user", prompt));
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChatGptResponse {
    private List<Choice> choices;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Choice {
        private int index;
        private Message message;
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {
    private String role;
    private String content;
}
//endpoint
GET /bot/chat?prompt=Hello