Integrating ChatGPT with Spring Boot: A Simple Guide

In today's world, chatbots and AI-powered conversational agents have become a vital component of applications, providing efficient and engaging user interactions. OpenAI's ChatGPT is at the forefront of this AI revolution, offering a powerful conversational AI model that can be seamlessly integrated into your Java applications with Spring Boot. In this blog, we will walk you through the process of integrating OpenAI's ChatGPT API into a Spring Boot application to create a responsive chatbot.

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.

Step-1 Spring Boot Project Setup

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

Step-2 Create config class

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();
                }
            }
            

Step-3 OpenAI API Setup

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

OpenAI Portal

create new secret key

OpenAI Portal

Choose Model Id from the OpenAI portal

OpenAI Portal

Step-4 Implement the ChatController

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;
              }

          }
          

Step-5 Test the API using Swagger or Postman

http://localhost:9090/chat?userInput=tell%20me%20a%20joke

swagger ui screen shot

swagger ui screen shot

Conclusion

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.


source code

Get in touch

Let’s work together

Reach out if you have a concept for a website or mobile app or require guidance with product design. contact me.
  info@whywhytechnova.com
  +(91) 88661 28862