Even more powerful, Java accesses ChatGPT API

This article describes how to interact with the ChatGPT API using Java, helping you integrate the power of the ChatGPT model into your Java applications!

Search on WeChat and follow “Java Learning and Research Base Camp”

Picture

As a large-scale language model trained by OpenAI, ChatGPT provides artificial intelligence services for natural language processing tasks. By using the ChatGPT API, developers can integrate the capabilities of the ChatGPT model into their applications. In this article, we will explore how to interact with the ChatGPT API using Java.

1 Step 1: Obtain API Key

Before you use the ChatGPT API, you need to obtain an API key from OpenAI. You can do this by creating an account on the OpenAI website and following the instructions to create a new API key. An API key is a long string of letters and numbers that you will use to authenticate your API requests.

Picture

2 Step 2: Set up Java environment

To send API requests from Java, you need to use a library that can make HTTP requests. We recommend using the OkHttp library because it is easy to use and widely supported.

To use OkHttp, you need to add the following dependencies to your Maven project:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version>
</dependency>

If you are not using Maven, you can download the OkHttp library from the official website and add it to your project manually.

3 Send API request

To send an API request, you need to send a POST request to the ChatGPT API endpoint. The endpoint URL is https://api.openai.com/v1/engine/davinci-codex/completions.

Here is an example of using OkHttp to send an API request:

import okhttp3.*;

public class ChatGPTClient {
    private static final String API_URL = "https://api.openai.com/v1/engines/davinci-codex/completions";

    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();

        String prompt = "My name is";
        String apiKey = "YOUR_API_KEY";

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{"prompt": "" + prompt + ""}");

        Request request = new Request.Builder()
                .url(API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Content-Type", "application/json")
                .build();

        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();

        System.out.println(responseBody);
    }
}

This code uses “Hello, my name is” as the prompt, sends a completion request to the ChatGPT API, and prints the response body to the console. You can modify the prompt and other parameters as needed.

4 Set request body

When sending an API request, the request body should contain a JSON object containing the parameters to complete the request. The required argument is “prompt”, which specifies the input text for which completion is to be generated. In addition to this, you can set optional parameters such as “temperature”, “max_tokens” and “top_p” to control the generation process.

Here is an example of completing the request JSON object:

{
    "prompt": "Hello, my name is",
    "temperature": 0.5,
    "max_tokens": 50,
    "top_p": 1,
    "frequency_penalty": 0,
    "presence_penalty": 0
}

You can modify the prompt and other parameters as needed. The meaning of each parameter is as follows:

- "prompt": Specifies the input text required for the build to complete.
- "temperature": Controls the randomness of the generation completion. Higher values will produce more random completions.
- "max_tokens": Specifies the maximum number of tokens (words or punctuation marks) included in each build completion.
- "top_p": Controls the completion diversity of the generation. Lower values produce more different finishes.
- "frequency_penalty": Penalize completion of words or phrases in repeated prompts.
- "presence_penalty": Penalty completions containing words or phrases that are not present in the prompt.

5 Processing API responses

After sending the API request, you will receive a JSON object containing the completion of the generation. The response format is as follows:

{
    "choices": [
        {
            "text": "My name is John.",
            "index": 0,
            "logprobs": null,
            "finish_reason": "stop"
        },
        {
            "text": "My name is Sarah.",
            "index": 1,
            "logprobs": null,
            "finish_reason": "stop"
        },
        {
            "text": "My name is David.",
            "index": 2,
            "logprobs": null,
            "finish_reason": "stop"
        }
    ]
}

The “choices” array contains one or more completions, each completion is represented by a JSON object with the following fields:

"text": Generated completion text.
"index": The index of the completion item in the generated completion list.
"logprobs": Log probabilities of completion marks, used for debugging purposes.
"finish_reason": The reason why the completion build stopped. Possible values include "stop", "max_tokens", "temperature", and "top_p".

You can use a JSON library such as Gson or Jackson to parse the response JSON object, the following is a sample code using Gson:

import com.google.gson.Gson;

public class ChatGPTClient {
    // ...
    
    public static void main(String[] args) throws Exception {
        // ...

        Gson gson = new Gson();
        ChatGPTResponse response = gson.fromJson(responseBody, ChatGPTResponse.class);
        for (ChatGPTCompletion completion : response.choices) {
            System.out.println(completion.text);
        }
    }
    
    private static class ChatGPTResponse {
        private ChatGPTCompletion[] choices;
    }
    
    private static class ChatGPTCompletion {
        private String text;
        private int index;
        private Object logprobs;
        private String finish_reason;
    }
}

This code uses Gson to parse the response JSON object into a Java object. The ChatGPTResponse class represents the top-level JSON object, and the ChatGPTCompletion class represents each completion object. The “text” field of each completion will be printed to the console.

6 Summary

This article explains how to interact with the ChatGPT API using Java. By sending an HTTP request with the correct headers and request body, and parsing the JSON response, you can integrate the power of the ChatGPT model into your Java application.

Recommended book list

IT BOOK Get a lot (click to view the 50% off activity book list)icon-default.png?t=N7T8https://u.jd.com/psx2y1M

“Java from Beginner to Master (7th Edition)”

“Java from Beginner to Master (7th Edition)” starts from the perspective of beginners and explains in detail the knowledge needed to use Java language for program development through easy-to-understand language and colorful examples. The book is divided into 4 parts with a total of 24 chapters, including first introduction to Java, development tools (IDEA, Eclipse), Java language basics, process control, arrays, classes and objects, inheritance, polymorphism, abstract classes and interfaces, packages and internal classes , exception handling, strings, common class libraries, collection classes, enumerated types and generics, lambda expressions and stream processing, I/O (input/output), reflection and annotations, database operations, Swing programming, Java drawing , multi-threading, concurrency, network communication, airplane war game, MR face recognition check-in system. All the knowledge in the book is explained with specific examples, and the involved program codes are given detailed comments, which can help readers easily understand the essence of Java program development and quickly improve development skills.

“Java from Beginner to Master (7th Edition)”icon-default.png?t=N7T8https://item.jd.com/14067396.html

Highlights

10 enterprise-level software architecture design patterns

8 drawing tools for drawing software architecture diagrams

10 must-know Spring Boot annotation methods

10 IntelliJ IDEA plug-ins you can’t miss

Which one is better and which one is worse? gRPC and Rest performance competition

Search on WeChat and follow “Java Learning and Research Base Camp”

Visit [IT Today’s Hot List] to discover daily technology hot spots

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139421 people are learning the system