Recently, ChatGPT has suddenly exploded in popularity. Holding a curious mind I also went to the official website to register an account to experience a bit, because the number of people on the site is too much, a moment and a half surprisingly can not be registered, but ultimately still successfully registered. Friends who have not registered can refer to this tutorial OpenAI launched the super god ChatGPT registration strategy came. Written in great detail, I will no longer explain.


After chatting with ChatGPT for about ten minutes, I was blown away by how clunky and robotic it looked, but it didn’t stop me from loving it. I thought about how I could incorporate it into our existing applications. So I took a look at the OpenAI website, and I realized that there are a lot of interfaces available for us to use.

 preliminary

 The ChatGPT API access requires the following conditions.

  1.  Successfully registered for an OpenAI account.

  2. Create API KEY, this API KEY is used for HTTP request authentication, you can create more than one. Click “Create new secret key” as below, note that you need to copy and save it immediately after creating it, you can’t see it after closing the popup box.

  1. Official API documentation link api-reference.

  2. Note that there is a charge for API calls, but OpenAI has given us a free $18 usage, enough for everyone to feel comfortable.

 Complementary Interface Example

 This interface is more functional and supports the most commonly used Q&A functions.

  1.  Request method, Post

  2. url, api.openai.com/v1/completi…
  3.  The request body (json).
{
  "model": "text-davinci-003",
  "prompt": "Say this is a test",
  "max_tokens": 7,
  "temperature": 0,
  "top_p": 1,
  "n": 1,
  "stream": false
}

  1. Interface documentation, platform.openai.com/docs/api-re…

 Request Parameter Analysis

model
Optional parameters. The language model, selected here, is text-davinci-003
prompt  Mandatory parameter. I.e., the user’s input.
max_tokens
Optional parameter, default value is 16. maximum number of participles, which affects the length of the returned result.
temperature
Optional parameter, default value is 1, takes the value 0-2. the larger the value, the more random the results returned each time, i.e. the smaller the similarity.
top_p  Optional parameter, similar to temperature .
n
Optional parameter, default value is 1. Indicates how many results are generated for each prompt .
stream
Optional parameter, default value is false . Indicates whether to reflow partial results.

 Example of a request


This article uses OkHttp as the web request framework and Moshi as the serialization/deserialization framework. Write a unit test to make a request to this interface with the following code.

  1.  Initialization of OkHttp.
private final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .callTimeout(60, TimeUnit.SECONDS)
        .build();
  1.  Request entity class.
private static class CompletionRequest {
    private String model = "text-davinci-003";
    private String prompt;
    private Integer max_tokens = 256;
    private float temperature = 0.5f;
    private Integer top_p = 1;
    private Integer n = 1;
    private Boolean stream = false;
    private Boolean logprobs;
    private String stop;
}
  1.  Request Method.


Use OkHttp to send the request. Note that all Post requests need to add the header field Authorization with a value of Bearer YOUR_API_KEY to authenticate.

public void completion(String prompt) throws IOException {
    CompletionRequest completionRequest = new CompletionRequest();
    completionRequest.setPrompt(prompt);

    String reqJson = moshi.adapter(CompletionRequest.class).toJson(completionRequest);
    System.out.println("reqJson: " + reqJson);
    Request request = new Request.Builder()
            .url("https://api.openai.com/v1/completions")              .header("Authorization", "Bearer " + API_KEY)
            .post(RequestBody.create(MEDIA_TYPE_JSON, reqJson))
            .build();

    try (Response response = okHttpClient.newCall(request).execute()) {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        System.out.println(response.body().string());
    }
}

  1. Call the completion(String prompt) method above in the completion() test method
@Test
public void completion() {
    try {
        chatGPT.completion("How many digits of pi can you memorize?");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1.  View request results
{
  "id": "cmpl-6j9PhjAom9GyxBNCVacvckcVNKVZg",
  "object": "text_completion",
  "created": 1676218965,
  "model": "text-davinci-003",
  "choices": [
    {
      "text": "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679。",
      "index": 0,
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 21,
    "completion_tokens": 73,
    "total_tokens": 94
  }
}


With the above example, I believe you have learned how to connect the ChatGPT API to your own application, OpenAI also provides other useful interfaces, we will not explain them one by one, you can go to the official website to check the documentation.

By lzz

Leave a Reply

Your email address will not be published. Required fields are marked *