Java에서 chatGPT API를 사용하려면 HTTP 요청을 수행할 수 있는 Java 라이브러리가 필요합니다. 그 중 하나인 Apache HttpClient 라이브러리를 사용할 수 있습니다.
먼저, Apache HttpClient 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용한다면 pom.xml
파일에 다음과 같은 종속성을 추가하면 됩니다.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
또는 Apache HttpClient 웹사이트에서 라이브러리를 다운로드해서 수동으로 프로젝트에 추가할 수도 있습니다.
Apache HttpClient 라이브러리가 프로젝트에 추가된 후에는 chatGPT API를 사용하여 응답을 생성하는 코드는 다음과 같습니다.
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ChatGPTExample {
public static void main(String[] args) {
// Replace YOUR_API_KEY with your actual API key
String apiKey = "YOUR_API_KEY";
// Set the model engine to use (in this case, chatGPT)
String modelEngine = "text-davinci-002";
// Set the prompt (the input to the model)
String prompt = "Hello, how are you today?";
// Set the maximum number of tokens (words) to generate in the response
int maxTokens = 1024;
// Set the temperature parameter (controls the randomness of the response)
float temperature = 0.5f;
// Create an HTTP client
CloseableHttpClient httpClient = HttpClients.createDefault();
// Create a POST request to the completions API
HttpPost request = new HttpPost("https://api.openai.com/v1/completions");
// Set the API key as a request header
request.setHeader("Authorization", "Bearer " + apiKey);
// Set the request body to a JSON object with the model, prompt, and other parameters
StringEntity requestBody = new StringEntity(
"{\"model\": \"" + modelEngine + "\", " +
"\"prompt\": \"" + prompt + "\", " +
"\"max_tokens\": " + maxTokens + ", " +
"\"temperature\": " + temperature + "}");
request.setEntity(requestBody);
// Send the request and get the response
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace
0 댓글