Java支持ChatGPT

 一、官方介绍

        使用OpenAI可参考官网的文档。官网给出了详细的参数解释、用例和使用方法的介绍。同时也罗列了计费规则和余额都查询。

OpenAI API官方文档

1.1 Documentation

在Documentation页面每个模型的MAX_TOKENS,表示输入的最大文本限制。

最大文本限制:请求+想用的单词数

每个模型允许的最大token数量不一样,比如gpt-3.5-turbo模型,允许最多有4096个token。

需要注意,这个数量既包括你输入的提示语,也包括AI产出的回答,两个加起来不能超过4096个token

比如,你的输入有1000个token,那么你这里设置的 max_tokens 就不能超过 3096。不然调用就会报错。

1.2 API reference

API reference介绍了API的参数解释,开发人员在开发过程中可参考文档进行开发

1.3 调用限制

        在实际调用API的过程中,出于对计算资源的保护,OpenAI还限制了各模型API的每分钟请求最大次数和每分钟Token通信量最大值

二、获取API Keys

根据自己的OpenAI账号,获取对应的API KEY,申请API KEY之后需保存下来,该Key是你用来调用接口的token,主要用于接口鉴权。

三、 代码实现

3.1 参数介绍

3.1.1 model

       model: 为必选参数. 指定使用的模型,常用:gpt-3.5-turbo、gpt-4o

3.1.2 Messages

        messages:为必选参数. 上下文列表,用于实现上下文对话. 必须为数组格式

        role:角色,可选值:system、user、assistant

                system:系统角色。可以帮助设定对话的语境,以便 AI 更好地理解其在对话中的角色

                user:表示用户的消息。

                assistant:表示助手(AI)的回复。

        content:必填. 消息体。也可以理解为提示词。

3.1.3 temperature

        temperature: 可选参数。取值范围为:0-2,默认值为1.参数代表采样温度,数值越小,模型会选择概率高的词汇,生成的文本更保守;数值越高,则会选择概率较低的词汇,生成的文本更多样化。

3.1.4 top_p

        top_p:可选参数。取值范围:0-1。作用与temperature类似,用于控制输出文本的随机性,数值越低,随机性越低,数值越高,随机性越高。通常来说,要调整随机性,top_p和temperature使用一个即可。

3.1.5 max_tokens

        max_tokens:可选参数。代表返回结果的token的数量。

3.1.6 其他参数可参考

        文章:OpenAI开发系列(六):Completions模型的工作原理及应用实例(开发多轮对话机器人)_如何做openai的上层应用-CSDN博客

3.2 简单使用

  • 请求地址和请求体
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'
  • 响应参数
{
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1677858242,
    "model": "gpt-3.5-turbo-0613",
    "usage": {
        "prompt_tokens": 13,
        "completion_tokens": 7,
        "total_tokens": 20
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "\n\nThis is a test!"
            },
            "logprobs": null,
            "finish_reason": "stop",
            "index": 0
        }
    ]
}

3.2.1 引入Pom文件

<dependencies>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.6</version>
    </dependency>
</dependencies>

3.3.2 主要Java代码实现

private String sendMessageToChatGpt(String translateMsgs)
      throws Exception {
    if (StringUtil.isNullOrBlank(translateMsgs)) {
      return null;
    }

    // 获取chatGpt配置
    String url = "https://api.openai.com/v1/chat/completions";
    if (StringUtil.isNullOrBlank(url)) {
      throw new Exception("ChatGpt地址未配置");
    }


    OkHttpClient.Builder clientBuilder = new OkHttpClient().newBuilder();
    // 设置代理(国内访问,需要使用;国外访问无需使用)
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7897));
    clientBuilder.proxy(proxy);
    OkHttpClient client = clientBuilder.build();

    // 构造请求体
    JsonObject message = new JsonObject();
    message.put("role", "user");
    message.put("content", "请帮我翻译成英文:" + translateMsgs);

    JsonArray messages = new JsonArray();
    messages.add(message);

    JsonObject jsonBody = new JsonObject();
    jsonBody.put("model", "gpt-4o");
    jsonBody.put("messages", messages);
    jsonBody.put("temperature", "0.7");

    RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"),
        jsonBody.toString());

    // 构造请求
    Request request = new Request.Builder().url(url).post(body)
        .addHeader("Content-Type", "application/json")
        .addHeader("Authorization", "Bearer " + API_KEYS).build();

    try (Response response = client.newCall(request).execute()) {
      if (!response.isSuccessful()) {
        throw new IOException("请求OpenAi失败:" + response);
      }

      // 解析响应
      String responseBody = response.body().string();
      JsonObject jsonResponse = new JsonObject(responseBody);
      JsonArray choices = jsonResponse.getJsonArray("choices");
      JsonObject firstChoice = choices.getJsonObject(0);
      JsonObject messageContent = firstChoice.getJsonObject("message");
      return messageContent.getString("content").trim();
    }
  }
  • 其中API_KEYS为自己账号申请的秘钥,替换即可使用

四、优秀框架和文章推荐

4.1 优秀框架

      PlexPt,可直接引入jar包,实现对接OpenAI的功能。

<dependency>
    <groupId>com.github.plexpt</groupId>
    <artifactId>chatgpt</artifactId>
    <version>4.1.2</version>
</dependency>

      Proxy proxy = Proxys.http("127.0.0.1", 7897);

      ChatGPT chatGPT = ChatGPT.builder()
                .apiKey(API_KEYS)
                .proxy(proxy)
                .timeout(3600)
                .apiHost("https://api.openai.com/v1/chat/completions")
                .build()
                .init();

        Message system = Message.ofSystem("帮我翻译一段话:你好世界");
        Message message = Message.of("写一段诗,主题:回家!");

        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .messages(Arrays.asList(system, message))
                .maxTokens(1000)
                .temperature(0.7)
                .build();
        ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
        Message res = response.getChoices().get(0).getMessage();

4.2 优秀文章

AI前线:AIGC与大模型的应用实例

  • 15
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java程序接入Chat GPT的步骤和代码实现: 1.前置准备: 在使用Chat GPT 2之前,需要先注册并获取API Key。注册地址为:https://www.chatie.io/register.html 2.官方支持接入语言: 目前Chat GPT 2官方支持的接入语言有:Python、Java、PHP、Node.js、Go、C#、Ruby、Shell、Perl、Swift、Objective-C、C++、Dart、Kotlin、Scala、Rust、Lua、Erlang、Haskell、Groovy、Clojure、OCaml、F#、Elixir、Julia、R、PowerShell、Scheme、Fortran、Ada、Prolog、Lisp、Bash、Tcl、Assembly、Smalltalk、Pascal、Visual Basic、COBOL、Logo、Forth、Rexx、Awk、sed、Yacc、Lex、M4、Makefile、Batch、ActionScript、ColdFusion、Delphi、Eiffel、Forth、FoxPro、IDL、LabVIEW、Matlab、Objective-C++、Perl6、PL/I、PostScript、RPG、SAS、SPSS、SQL、Verilog、VHDL、XSLT等。 3.调用费用: Chat GPT 2提供免费试用,每个月可以免费调用1000次API,超过1000次需要付费。 4.接口调用说明: Chat GPT 2的API接口地址为:https://api.chatie.io/chatgpt2/ask 请求方式为POST,请求参数为text和apikey,其中text为输入的文本,apikey为注册时获取的API Key。 5.代码实现: 以下是Java程序调用Chat GPT 2的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class ChatGPT2Demo { public static void main(String[] args) { String question = "你好"; String apiKey = "your_api_key"; try { String urlStr = "https://api.chatie.io/chatgpt2/ask?text=" + URLEncoder.encode(question, "UTF-8") + "&apikey=" + apiKey; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 6.小结: 以上就是Java程序接入Chat GPT 2的全部步骤和代码实现,通过以上步骤可以轻松地在Java程序中接入Chat GPT 2,实现智能问答功能。 --相关***. Chat GPT 2的免费试用次数是多少?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值