You are currently viewing Using OpenAI ChatGPT APIs in Spring Boot

Using OpenAI ChatGPT APIs in Spring Boot

In this tutorial, we will explore how to integrate OpenAI’s ChatGPT API into a Spring Boot application. OpenAI’s ChatGPT API allows us to create conversational AI models for various applications like chatbots, customer support systems, and more. We’ll walk through the process of setting up a Spring Boot application and making requests to the ChatGPT API.

Prerequisites

  • Basic knowledge of Spring Boot
  • Java Development Kit (JDK) installed
  • OpenAI API key (sign up at OpenAI’s website)

Step 1: Create a Spring Boot Application

If you don’t have a Spring Boot application set up yet, you can quickly create one using Spring Initializr.

  1. Go to Spring Initializr.
  2. Fill in the project details:
  • Project: Gradle or Maven (Choose your build system)
  • Language: Java
  • Spring Boot: Choose the latest stable version
  • Group: com.example
  • Artifact: chatgpt-demo
  • Dependencies: Web
  1. Click “Generate” to download the project zip file.
  2. Extract the downloaded zip file to a folder on your computer.

Step 2: Add OpenAI API Dependency

We’ll need to add the org.openai dependency to our build.gradle (for Gradle) or pom.xml (for Maven) file.

For Gradle (build.gradle):

dependencies {
    implementation 'org.openai:openai-api-java:1.0.0'
}

For Maven (pom.xml):

<dependency>
    <groupId>org.openai</groupId>
    <artifactId>openai-api-java</artifactId>
    <version>1.0.0</version>
</dependency>

Step 3: Configure OpenAI API Key

We’ll store our OpenAI API key as an environment variable or in the application.properties file.

Using application.properties:

Add your API key to src/main/resources/application.properties:

openai.api-key=YOUR_OPENAI_API_KEY

Using Environment Variable:

Set an environment variable OPENAI_API_KEY with your API key.

Step 4: Create ChatGPTService

Let’s create a ChatGPTService class to handle interactions with the OpenAI ChatGPT API.

import org.openai.OpenAI;
import org.openai.models.ChatCompletionRequest;
import org.openai.models.ChatCompletionResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ChatGPTService {

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

    public String getChatResponse(String prompt) {
        OpenAI openAI = new OpenAI(apiKey);

        ChatCompletionRequest request = new ChatCompletionRequest();
        request.setPrompt(prompt);
        request.setMax_tokens(100);
        request.setModel("gpt-3.5-turbo");

        ChatCompletionResponse response = openAI.createChatCompletion(request);

        return response.getChoices().get(0).getText();
    }
}

Step 5: Create a Controller

Next, let’s create a REST controller to expose an endpoint for getting a ChatGPT response.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatGPTController {

    @Autowired
    private ChatGPTService chatGPTService;

    @PostMapping("/chat")
    public String getChatResponse(@RequestBody String prompt) {
        return chatGPTService.getChatResponse(prompt);
    }
}

Step 6: Run the Application

Now we can run our Spring Boot application. If you are using Gradle, run:

./gradlew bootRun

For Maven, use:

./mvnw spring-boot:run

Step 7: Test the API

You can now test the API using tools like cURL, Postman, or simply a web browser.

Using cURL:

curl -X POST http://localhost:8080/chat -H "Content-Type: application/json" -d '{"prompt":"Hello, how are you?"}'

Using Postman:

  • Create a POST request to http://localhost:8080/chat
  • Set the body as raw JSON:
  {
    "prompt": "Hello, how are you?"
  }

Using Browser:

Navigate to http://localhost:8080/chat with a JSON payload:

{
  "prompt": "Hello, how are you?"
}

Conclusion

You have now created a simple Spring Boot application that integrates with OpenAI’s ChatGPT API. This setup allows you to send prompts to the ChatGPT model and receive responses. Remember to handle exceptions, add error checking, and consider security measures when building a production application. This example provides a starting point for more complex integrations and applications utilizing the power of ChatGPT.

Leave a Reply