2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPT API Javaバージョン

Last updated at Posted at 2023-03-02

以下のコードでJavaでChatGPTのAPIにアクセスできます。

■Maven

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.8</version>
</dependency>

■Java

package com.example.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Controller
@RequestMapping("")
public class TestChatCompletionController {

	@RequestMapping("")
	public String openAIChat() {
		
        String url = "https://api.openai.com/v1/chat/completions";
        String api_key = System.getenv("OPENAI_API_KEY");
        String model = "gpt-3.5-turbo";
        String message = "{\"role\": \"user\", \"content\": \"Hello!\"}";

        try {
        	// HTTPリクエストの作成
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", "Bearer " + api_key);
            con.setDoOutput(true);

            // リクエストの送信
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write("{\"model\": \"" + model + "\", \"messages\": [" + message + "]}");
            out.close();

            // レスポンスの取得
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            Gson gson = new Gson();
            JsonObject jsonResponse = gson.fromJson(in, JsonObject.class);
            JsonArray choicesArray = jsonResponse.getAsJsonArray("choices");
            JsonObject messageObject = choicesArray.get(0).getAsJsonObject().get("message").getAsJsonObject();
            String content = messageObject.get("content").getAsString();

            // レスポンスの出力
            System.out.println(content);
        } catch (Exception e) {
            System.out.println(e);
        }	
        return "start";
	}
}

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?