How to Interact with OpenAI APIs Using Java

In this tutorial, we will guide you through the process of interacting with OpenAI APIs using Java. We will use the Jackson library for JSON parsing and the HttpClient class to make HTTP requests.

Prerequisites

  • Java 11 or later
  • Maven 3.6.3 or later
  • OpenAI API Key

Step-by-Step Guide

Step 1: Set Up Your Project

First, create a new Maven project or add the necessary dependencies to your existing project.

Add Dependencies

Add the following dependencies to your pom.xml:

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.12.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.12.3</version>
    </dependency>
</dependencies>

Step 2: Create Data Models

Define the data models that represent the request and response structures.

ChatGPTRequest.java

package com.example.demo.model;

import java.util.List;

public class ChatGPTRequest {
    private String model;
    private List<Message> messages;

    // Getters and setters

    public static class Message {
        private String role;
        private String content;

        // Getters and setters
    }
}

ChatGPTResponse.java 

package com.example.demo.model;

import java.util.List;

public class ChatGPTResponse {
    private List<Choice> choices;

    // Getters and setters

    public static class Choice {
        private Message message;

        // Getters and setters
    }

    public static class Message {
        private String role;
        private String content;

        // Getters and setters
    }
}

Step 3: Create the OpenAI Client

Create a service class to handle the interactions with the OpenAI API.

OpenAIClient.java

package com.example.demo.service;

import com.example.demo.model.ChatGPTRequest;
import com.example.demo.model.ChatGPTResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class OpenAIClient {

    private final String apiKey = "your_openai_api_key";
    private final String apiUrl = "https://api.openai.com/v1/chat/completions";

    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;

    public OpenAIClient() {
        this.httpClient = HttpClient.newHttpClient();
        this.objectMapper = new ObjectMapper();
    }

    public String getChatGPTResponse(String userMessage) throws Exception {
        ChatGPTRequest.Message userMsg = new ChatGPTRequest.Message();
        userMsg.setRole("user");
        userMsg.setContent(userMessage);

        ChatGPTRequest request = new ChatGPTRequest();
        request.setModel("gpt-3.5-turbo");
        request.setMessages(List.of(userMsg));

        String requestBody = objectMapper.writeValueAsString(request);

        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(new URI(apiUrl))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
                .build();

        HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            ChatGPTResponse chatGPTResponse = objectMapper.readValue(response.body(), ChatGPTResponse.class);
            if (chatGPTResponse.getChoices() != null && !chatGPTResponse.getChoices().isEmpty()) {
                return chatGPTResponse.getChoices().get(0).getMessage().getContent();
            } else {
                return "No response from ChatGPT";
            }
        } else {
            throw new RuntimeException("Error: " + response.body());
        }
    }
}

Step 4: Create a Main Class

Create a main class to test the interaction with the OpenAI API.

Main.java

package com.example.demo;

import com.example.demo.service.OpenAIClient;

public class Main {
    public static void main(String[] args) {
        OpenAIClient openAIClient = new OpenAIClient();
        try {
            String response = openAIClient.getChatGPTResponse("Hello, how are you?");
            System.out.println("Response from ChatGPT: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 5: Run the Application

Compile and run your Java application. You should see the response from the OpenAI API in the console.

Conclusion

This tutorial demonstrated how to interact with OpenAI APIs using Java. We used the Jackson library for JSON parsing and the HttpClient class for making HTTP requests. By following these steps, you can integrate OpenAI's powerful AI capabilities into your Java applications, enabling you to build intelligent and interactive systems.


Comments