免费的直接访问的ChatGPT接口,自己DIY才是王道!

前言

最近小编观察到,很多免费的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地址!

猜你喜欢

转载自juejin.im/post/7217279252314980412
今日推荐