前言
最近小编观察到,许多免费的GPT体会网页,要么开始收费,要么GG了或国内不方便直接拜访。也给我们学习沟通供给了很大的阻止,都不能好好的玩耍了!所以我这里供给一个免费ChatGPT API接口
,供我们学习沟通!
供给两种API拜访形式,我们可根据自己需求选择
- SSE(Server Sent-Events)流的方式
- HTTP直接拜访(可能会有点慢,因为需求接纳完所有的流数据才会回来)
1. 根据SSE(Server Sent-Events)回来数据 – /gpt/chat/stream
示例代码中依赖的三方包:
- OkHttp3
- FastJson2
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.24</version>
</dependency>
Java代码示例:
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
//提问的问题
RequestBody requestBody = RequestBody.create(JSON.toJSONString(Map.of(
"input", "你是谁?"
)), MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url("https://xxx/gpt/chat/stream")
.post(requestBody)
.headers(Headers.of(Map.of("Content-Type", "application/json; charset=utf-8")))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
throw new ApiException("API异常:" + e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
//接纳呼应流
BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("接纳处理内容:" + line);
}
} catch (Exception e) {
throw new ApiException(e.getMessage());
}
}
});
}
呼应信息:
接纳处理内容:我是ChatGPT,一个由OpenAI练习的大型语言模型。
2. HTTP直接恳求取得结果 – /gpt/chat
Java代码示例:
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(JSON.toJSONString(Map.of(
"input", "你是谁?用英文回复"
)), MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url("https://xxx/gpt/chat/stream")
.post(requestBody)
.headers(Headers.of(Map.of("Content-Type", "application/json; charset=utf-8")))
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("呼应信息:" + response.body().string());
}
}
呼应内容:
呼应信息:I am ChatGPT, a large language model trained by OpenAI.
声明
本文章供给的接口,不能作为出产环境使用。一起为了仅供有爱好的同学使用,设置了门槛,需求从大众号(搞IT的成龙同学)获取完整API恳求方式,要不然都直接拜访,小服务器可扛不住!
留意:发送
GPT
即可获取API地址!