java如何调用chatgpt
时间: 2023-09-10 19:11:47 浏览: 203
chatgpt开源项目,无需调用AIP接口,不需要联网即可运行的chatgpt,里面代码完整,有word操作手册,可做毕业设计
在Java中调用ChatGPT,可以使用OpenAI的相关API来实现。下面是一个简单的示例代码:
```java
import okhttp3.OkHttpClient;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class ChatGPTCaller {
private static final String API_URL = "https://api.openai.com/v1/chat/completions";
private static final String API_KEY = "YOUR_API_KEY";
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"model\": \"gpt-3.5-turbo\",\"messages\": [{\"role\": \"system\",\"content\": \"You are a helpful assistant.\"},{\"role\": \"user\",\"content\": \"Who won the world series in 2020?\"},{\"role\": \"assistant\",\"content\": \"The Los Angeles Dodgers won the World Series in 2020.\"},{\"role\": \"user\",\"content\": \"Where was it played?\"},{\"role\": \"assistant\",\"content\": \"The World Series in 2020 was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.\"}]}\n");
Request request = new Request.Builder()
.url(API_URL)
.post(body)
.addHeader("Authorization", "Bearer " + API_KEY)
.addHeader("Content-Type", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,你需要替换`YOUR_API_KEY`为你自己的API密钥。还需要根据对话的内容设置`messages`数组中不同角色的消息。
在这个示例中,我们将使用OpenAI的GPT-3.5-turbo模型,它不需要设置初始文本。你可以根据自己的需求进行调整。
请确保你已经正确引入OkHttp库,并且已经获取到了有效的API密钥。
阅读全文