java输出一个chatgpt
时间: 2023-10-01 10:03:47 浏览: 110
作为AI语言模型的GPT,需要通过API接口进行调用,获取相应的文本输出。以下是使用Java调用OpenAI GPT-3 API输出chatbot的示例代码:
```java
import java.net.*;
import java.io.*;
import java.util.*;
public class Chatbot {
public static void main(String[] args) throws Exception {
String prompt = "Hello, how are you today?";
String apikey = "YOUR_API_KEY_HERE";
String url = "https://api.openai.com/v1/engines/davinci-codex/completions";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + apikey);
String postJsonData = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": 100, \"temperature\": 0.7}";
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(postJsonData.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String output = response.toString();
output = output.substring(output.indexOf("\"text\":") + 8, output.length() - 3);
System.out.println(output);
}
}
```
需要将YOUR_API_KEY_HERE替换为你的OpenAI API密钥。运行程序后,将输出一个与输入prompt相关的chatbot回复。
阅读全文