【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果

java如何快速对接海外大模型实现打字机效果-chat模式

前言

随着海外模型的热度胜起,海外各种模型开始兴起,但是由于初学者对环境的部署和海外支付阻扰,对海外模型学习难度增加,接下来会介绍如何各种方式快速调用海外模型,并且给出案例和效果。


一、如何使用原生http调用?

1. 引入http框架okhttpclient及其相应的包

java 复制代码
<dependency>
   <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.36</version>
</dependency>

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

2.非流

java 复制代码
public class GptChatDemo {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class GptChatRequest {
        private String model;
        private List<Message> messages;
        private boolean stream;
    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Message {
        private String role;
        private String content;
    }

    private static String url = "https://www.apiplus.online/v1/chat/completions";
    private static String token = "sk-aZ8OTonNtI7jo5bDQtwcbTsg0z4giYiH9Ax6wleLpRGlX4NP"; // 替换为实际的API令牌


    public static void main(String[] args) throws IOException {
        Message message = new Message();
        message.setRole("user");
        message.setContent("你好");
        GptChatRequest gptChatRequest = new GptChatRequest();
        gptChatRequest.setModel("gpt-4o-mini");
        gptChatRequest.setStream(false);
        gptChatRequest.setMessages(Collections.singletonList(message));

        String response = sendNoStreamRequest(url, token, gptChatRequest);
        System.out.println(response);

        gptChatRequest.setStream(true);
        sendStreamRequest(url, token, gptChatRequest);
    }


    private static void sendStreamRequest(String url, String apiKey, GptChatRequest gptChatRequest) throws IOException {
        // 实现发送请求的逻辑
        String jsonString = JSONObject.toJSONString(gptChatRequest);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
        Request.Builder builder = new Request.Builder().url(url).method("POST", body)
                .addHeader("Authorization", "Bearer " + apiKey);
        Request request = builder.build();
        OkHttpClient client = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectionPool(new ConnectionPool(8000, 300, TimeUnit.SECONDS))
                .readTimeout(600, TimeUnit.SECONDS)
                .writeTimeout(600, TimeUnit.SECONDS)
                .build();
        Response execute = client.newCall(request).execute();
        ResponseBody responseBody = execute.body();
        Reader reader = Objects.requireNonNull(responseBody).charStream();
        BufferedReader bufferedReader = new BufferedReader(reader);

        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
    }


    private static String sendNoStreamRequest(String url, String apiKey, GptChatRequest gptChatRequest) throws IOException {
        // 实现发送请求的逻辑
        String jsonString = JSONObject.toJSONString(gptChatRequest);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
        Request.Builder builder = new Request.Builder().url(url).method("POST", body)
                .addHeader("Authorization", "Bearer " + apiKey);
        Request request = builder.build();
        OkHttpClient client = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectionPool(new ConnectionPool(8000, 300, TimeUnit.SECONDS))
                .readTimeout(600, TimeUnit.SECONDS)
                .writeTimeout(600, TimeUnit.SECONDS)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

总结

以上可以无缝的使用java调用非流的,并且给出了相应的使用key去使用

github代码仓库 github.com/EroAI-Free/...

gitee代码仓库: gitee.com/lixinjiuhao...

相关推荐
Seven973 分钟前
剑指offer-74、n个骰⼦的点数
java
步步为营DotNet1 小时前
深度解析CancellationToken:.NET中的优雅取消机制
java·前端·.net
JH30739 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
Coder_Boy_10 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
invicinble11 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟11 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖11 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
qq_124987075312 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
Coder_Boy_12 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Mr_sun.12 小时前
Day06——权限认证-项目集成
java