用java写一个chatgpt的调用代码
时间: 2023-06-13 10:03:53 浏览: 109
由于目前还没有Java官方提供的GPT-3 API,以下代码是基于OpenAI提供的GPT-3 API示例进行的,仅供参考:
```java
import java.io.*;
import java.net.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class ChatGPT {
private static final String API_KEY = "YOUR_API_KEY";
private static final String ENDPOINT = "https://api.openai.com/v1/engines/davinci-codex/completions";
private static final String PROMPT = "Hello, how can I help you today?";
public static void main(String[] args) throws Exception {
String input = "";
Scanner scanner = new Scanner(System.in);
while (!input.equalsIgnoreCase("exit")) {
System.out.print("You: ");
input = scanner.nextLine();
String response = getResponse(input);
System.out.println("ChatGPT: " + response);
}
}
private static String getResponse(String input) throws Exception {
URL url = new URL(ENDPOINT);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setDoOutput(true);
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("prompt", PROMPT + "\nUser: " + input + "\nChatGPT:");
OutputStream os = conn.getOutputStream();
os.write(jsonRequest.toJSONString().getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
JSONObject jsonResponse = (JSONObject) new JSONParser().parse(sb.toString());
JSONArray choices = (JSONArray) jsonResponse.get("choices");
JSONObject choice = (JSONObject) choices.get(0);
return choice.get("text").toString().trim();
}
}
```
需要注意的是,此代码需要引入json-simple库,可以通过Maven或其他方式进行导入。同时,需要将API_KEY替换为你自己的API密钥。
阅读全文