API Coding
API (Application Programming Interface) Coding Guide


Using OpenAI ChatGPT API with Java

Posted on

Here's a step-by-step guide on how to use the OpenAI ChatGPT API with Java:

First, you'll need to create an account on the OpenAI platform and obtain an API key. You can sign up for free at https://beta.openai.com/signup/.

Once you have your API key, you can use a Java library like Retrofit to interact with the OpenAI API. Retrofit is a type-safe HTTP client for Java that makes it easy to send HTTP requests and parse the responses.

To get started with Retrofit, you'll need to add the following dependencies to your Java project:

<dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>converter-gson</artifactId> <version>2.9.0</version> </dependency>

These dependencies include Retrofit itself and the Gson converter, which allows you to parse JSON responses from the OpenAI API.

Next, you'll need to define a Java interface that describes the endpoints of the OpenAI API you want to call. Here's an example interface that defines a single endpoint for generating text with the ChatGPT API:


import retrofit2.Call;
import retrofit2.http.*;

public interface OpenAIChatGPTAPI {
    @POST("completions")
    @Headers({
            "Content-Type: application/json",
            "Authorization: Bearer YOUR_API_KEY"
    })
    Call generateText(@Body OpenAIRequest request);
}

This interface defines a single method called generateText() that takes an OpenAIRequest object as input and returns an OpenAIResponse object. The @POST annotation specifies that this method sends an HTTP POST request to the /completions endpoint of the OpenAI API. The @Headers annotation specifies the Content-Type and Authorization headers required for the API request. You'll need to replace YOUR_API_KEY with your actual OpenAI API key.

Next, you'll need to define the OpenAIRequest and OpenAIResponse classes that Retrofit will use to serialize and deserialize JSON data to and from the API. Here's an example OpenAIRequest class that defines a simple request to generate text:


import com.google.gson.annotations.SerializedName;

public class OpenAIRequest {
    @SerializedName("prompt")
    public String prompt;

    @SerializedName("temperature")
    public double temperature;

    @SerializedName("max_tokens")
    public int maxTokens;

    public OpenAIRequest(String prompt, double temperature, int maxTokens) {
        this.prompt = prompt;
        this.temperature = temperature;
        this.maxTokens = maxTokens;
    }
}

This class has three fields that correspond to the input parameters of the /completions endpoint: prompt, temperature, and max_tokens. The @SerializedName annotation specifies the JSON field names that correspond to each Java field.

Finally, you can use the OpenAIChatGPTAPI interface to generate text with the ChatGPT API. Here's an example Java program that generates a single response from the API:


import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class OpenAIChatGPTExample {
    public static void main(String[] args) throws Exception {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.openai.com/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();