以下のコードで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";
}
}