手摸手带你免费使用GPT API

556 阅读4分钟

前言

嗨,大家好,好久不见,我是雪荷,这次我带大家免费白嫖 ChatGPT API。

领取 API token

首先访问 ChatAnyWhere 的仓库(github.com/chatanywher…),它是 那个GPT的国内代理服务,支持使用多种模型,如 gpt-4o-mini,gpt-3.5-turbo 等等,但是每天只有 200 次免费额度,但也够用了。但是使用 gpt-4o 等模型需要付费,不过价格比官方便宜多了,购买链接:ChatAnywhere

先点击框内链接,随后复制 API Key。拿到 API key 我们就可以直接使用啦。

image-20250111132944329

编辑

image-20250111133111471

编辑

配合 Chatbox 使用

Chatbox 是一个 AI 客户端应用,支持多种大模型和 API,访问官网(Chatbox AI官网:办公学习的AI好助手,全平台AI客户端,官方免费下载)直接下载即可。随后打开软件点击设置,输入刚刚的 API key 和 API 域名(ChatAnywhere)并选择模型保存后即可使用了。

image-20250111133425830

编辑

随便创建一个对话,测试能否可用。可以看到像响应速度还是很快的,并且还能看到使用的 token 数。

image-20250111134709294

编辑

Java 代码调用 GPT API

通过如下代码调用 GPT,将“AIConstant.SYSTEM_PROMPT_PRO”替换为你的 API key ,随后将messageObj.addProperty("content", "你好,你是谁?");更改 content 为你要发送的消息即可完成调用。

package com.hjj.lingxibi;
​
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hjj.lingxibi.common.ErrorCode;
import com.hjj.lingxibi.constant.AIConstant;
import com.hjj.lingxibi.exception.BusinessException;
import okhttp3.*;
​
public class Main {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        Gson gson = new Gson();
​
        // 选择模型
        JsonObject json = new JsonObject();
        json.addProperty("model", "gpt-4o-mini");
​
        JsonArray messages = new JsonArray();
        JsonObject messageObj = new JsonObject();
        // 添加用户发送的消息
        messageObj.addProperty("role", "user");
        messageObj.addProperty("content", "你好,你是谁?");
        messages.add(messageObj);
        json.add("messages", messages);
        json.addProperty("temperature", 0.7);
​
        String jsonString = gson.toJson(json);
​
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonString, mediaType);
        Request request = new Request.Builder()
                .url(AIConstant.CHATGPT_API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + AIConstant.CHATGPT_API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();
​
        String responseBody = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                String errorResponse = response.body().string();
                throw new BusinessException(ErrorCode.THIRD_SERVICE_ERROR, errorResponse);
            }
            responseBody = response.body().string();
            System.out.println(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
​
    }
}

调用结果如下:

image-20250111134207270

编辑

{"id":"chatcmpl-AoOXgxIIIYCDw3SihzrMoUId4MV8E","choices":[{"index":0,"message":{"role":"assistant","content":"你好!我是一个人工智能助手,旨在回答你的问题和提供帮助。有什么我可以为你做的呢?"},"logprobs":null,"finish_reason":"stop"}],"created":1736574104,"model":"gpt-4o-mini-2024-07-18","object":"chat.completion","usage":{"prompt_tokens":11,"completion_tokens":26,"total_tokens":37,"completion_tokens_details":{"audio_tokens":0,"reasoning_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0}},"system_fingerprint":"fp_5154047bf2"}

可以通过正则表达式拿到 ChatGPT 恢复的信息,这里就不掩饰了。

如果要给 AI 设置 prompt 就加个 system 的角色即可,具体代码如下:

package com.hjj.lingxibi;
​
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hjj.lingxibi.common.ErrorCode;
import com.hjj.lingxibi.constant.AIConstant;
import com.hjj.lingxibi.exception.BusinessException;
import okhttp3.*;
​
public class Main {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        Gson gson = new Gson();
​
        // 选择模型
        JsonObject json = new JsonObject();
        json.addProperty("model", "gpt-4o-mini");
​
        JsonArray messages = new JsonArray();
        JsonObject systemMessage = new JsonObject();
        JsonObject messageObj = new JsonObject();
        // 添加 system 消息 / AI prompt
        systemMessage.addProperty("role", "system");
        systemMessage.addProperty("content", "将我发送的消息翻译为英文,不要生成多余内容");
        messages.add(systemMessage);
        // 添加用户发送的消息
        messageObj.addProperty("role", "user");
        messageObj.addProperty("content", "今天天气真好啊,和我一起散步好吗?");
        messages.add(messageObj);
        json.add("messages", messages);
        json.addProperty("temperature", 0.7);
​
        String jsonString = gson.toJson(json);
​
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonString, mediaType);
        Request request = new Request.Builder()
                .url(AIConstant.CHATGPT_API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + AIConstant.CHATGPT_API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();
​
        String responseBody = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                String errorResponse = response.body().string();
                throw new BusinessException(ErrorCode.THIRD_SERVICE_ERROR, errorResponse);
            }
            responseBody = response.body().string();
            System.out.println(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
        }
​
    }
}

调用结果如下:

image-20250111134531518

编辑

{"id":"chatcmpl-AoOb4R5Z3Dul1SPBnrN8vbP9vL1Em","choices":[{"index":0,"message":{"role":"assistant","content":"The weather is really nice today. Would you like to take a walk with me?"},"logprobs":null,"finish_reason":"stop"}],"created":1736574314,"model":"gpt-4o-mini-2024-07-18","object":"chat.completion","usage":{"prompt_tokens":40,"completion_tokens":17,"total_tokens":57,"completion_tokens_details":{"audio_tokens":0,"reasoning_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cached_tokens":0}},"system_fingerprint":"fp_5154047bf2"}

开源项目

前一阵子,我开源了一个既好玩又能学到东西的项目,有兴趣的同学可以移步学习和体验哈——我终于有我的开源项目了!!!-CSDN博客