java如何对接cahtgpt API(简单记录)

这篇具有很好参考价值的文章主要介绍了java如何对接cahtgpt API(简单记录)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

java如何对接cahtgpt API(简单记录)

技术选型

springboot+mybatis-plus

实现效果

  • 通过java调用chatgpt API实现对话,将chatgpt生成的内容通过与前端建立websocket及时发送给前端,为加快chatgpt响应速度,采用exent/stream的方式进行,实现了逐字出现的效果

实现过程

java对接chatgpt API
  • 使用java原生的网络请求方式完成
    • 在发送网络请求时,将"stream"设置为 true,代表使用event stream的方式进行返回数据
  String url = "https://api.openai.com/v1/chat/completions";
        HashMap<String, Object> bodymap = new HashMap<>();

        bodymap.put("model", "gpt-3.5-turbo");
        bodymap.put("temperature", 0.7);
//        bodymap.put("stream",true);
        bodymap.put("messages", messagelist);
        bodymap.put("stream", true);
        Gson gson = new Gson();
        String s = gson.toJson(bodymap);
//        System.out.println(s);
        URL url1 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)));
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + ApiKey);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("stream", "true");
        conn.setDoOutput(true);
//    写入请求参数
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));
        writer.write(s);
        writer.close();
        os.close();

       
  • 读取返回值

     InputStream inputStream = conn.getInputStream();
    
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
    //        System.out.println("开始回答");
            StringBuffer answoer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
    
                line = line.replace("data:", "");
                JsonElement jsonElement = JsonParser.parseString(line);
                if (!jsonElement.isJsonObject()) {
    
                    continue;
                }
                JsonObject asJsonObject = jsonElement.getAsJsonObject();
                JsonArray choices = asJsonObject.get("choices").getAsJsonArray();
                if (choices.size() > 0) {
                    JsonObject choice = choices.get(0).getAsJsonObject();
                    JsonObject delta = choice.get("delta").getAsJsonObject();
                    if (delta != null) {
    //                    System.out.println(delta);
                        if (delta.has("content")) {
    //                        发送消息
                            String content = delta.get("content").getAsString();
                            BaseResponse<String> success = ResultUtils.success(content);
                            WebSocket webSocket = new WebSocket();
    
                            webSocket.sendMessageByUserId(conversionid, gson.toJson(success));
                            answoer.append(content);
    //                        webSocket.sendOneMessage(userid, success);
    //                        webSocket.sendOneMessage(userid, success);
    //                      打印在控制台中
                            System.out.print(content);
                        }
                    }
                }
    
            }
            String context = answoer.toString();
            //        将chatgpt返回的结果保存到数据库中
            Chat entity = new Chat();
            entity.setContext(context);
            entity.setRole("assistant");
            entity.setConversionid(conversionid);
            boolean save = chatService.save(entity);
    
    
    //        String s1 = stringRedisTemplate.opsForValue().get("web:" + userid);
    //        List<ChatModel> json = (List<ChatModel>) gson.fromJson(s1, new TypeToken<List<ChatModel>>() {
    //        }.getType());
    //        ChatModel chatModel = new ChatModel("assistant",answoer.toString());
    //        json.add(chatModel);
    //        stringRedisTemplate.opsForValue().set("web:" + userid,gson.toJson(json),1, TimeUnit.DAYS);
    
        }
    
实现websocket与前端建立连接
@ServerEndpoint(value = "/websocket/{ConversionId}")
@Component
public class WebSocket {

    private static ChatGptUntil chatGptUntil;

    private static ChatService chatService;

    private static ConversionService conversionService;

    @Resource
    public void setConversionService(ConversionService conversionService) {
        WebSocket.conversionService = conversionService;
    }

    @Resource
    public void setChatService(ChatService chatService) {
        WebSocket.chatService = chatService;
    }

    @Resource
    public void setChatGptUntil(ChatGptUntil chatGptUntil) {
        WebSocket.chatGptUntil = chatGptUntil;
    }

    private final static Logger logger = LogManager.getLogger(WebSocket.class);

    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的
     */

    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象
     */
    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */

    private Session session;
    private Long ConversionId;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("ConversionId") Long ConversionId) {
        this.session = session;
        this.ConversionId = ConversionId;
        //加入map
        webSocketMap.put(ConversionId.toString(), this);
        addOnlineCount();           //在线数加1
        logger.info("对话{}连接成功,当前在线人数为{}", ConversionId, getOnlineCount());
        try {
            sendMessage(String.valueOf(this.session.getQueryString()));
        } catch (IOException e) {
            logger.error("IO异常");
        }
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从map中删除
        webSocketMap.remove(ConversionId.toString());
        subOnlineCount();           //在线数减1
        logger.info("对话{}关闭连接!当前在线人数为{}", ConversionId, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        logger.info("来自客户端对话:{} 消息:{}", ConversionId, message);


        Gson gson = new Gson();

//        ChatMessage chatMessage = gson.fromJson(message, ChatMessage.class);

        System.out.println(message);

//        Long conversionid = chatMessage.getConversionid();
//        if (conversionid == null) {
//            BaseResponse baseResponse = ResultUtils.error(4000, "请指明是哪个对话");
//            String s = gson.toJson(baseResponse);
//            session.getBasicRemote().sendText(s);
//        }

        if (message == null) {
            BaseResponse baseResponse = ResultUtils.error(4000, "请指明是该对话的用途");
            String s = gson.toJson(baseResponse);
            session.getBasicRemote().sendText(s);
        }
//        将对话保存到数据库中
        Chat entity = new Chat();
        entity.setContext(message);
        entity.setConversionid(this.ConversionId);
        entity.setRole("user");
        boolean save = chatService.save(entity);

        if (!save) {
            BaseResponse baseResponse = ResultUtils.error(500, "数据库出现错误");
            String s = gson.toJson(baseResponse);
            session.getBasicRemote().sendText(s);
        }


//        查询出身份
        Conversion byId = conversionService.getById(this.ConversionId);
        String instructions = byId.getInstructions();// 指令
//     给予chatgot身份
        ArrayList<ChatModel> chatModels = new ArrayList<>();
//        ChatModel scene = new ChatModel("user", instructions);
//        chatModels.add(scene);

        LambdaQueryWrapper<Chat> queryWrapper = new LambdaQueryWrapper<>();
        // 按照修改时间进行升序排序
        queryWrapper.eq(Chat::getConversionid, byId.getId()).orderByDesc(Chat::getUpdatedtime);
        List<Chat> list = chatService.list(queryWrapper);

//        查询之前的对话记录
        List<ChatModel> collect = list.stream().map(chat -> {
            ChatModel chatModel = new ChatModel();
            chatModel.setRole(chat.getRole());
            chatModel.setContent(chat.getContext());
//            BeanUtils.copyProperties(chat, chatModel);
            return chatModel;
        }).collect(Collectors.toList());
        chatModels.addAll(collect);


        chatGptUntil.getRespost(this.ConversionId, chatModels);
//        if (chatGptUntil==null){
//            System.out.println("chatuntil是空");
//        }
//
//        if (stringRedisTemplate==null){
//            System.out.println("缓存是空");
//        }


        //群发消息
        /*for (String item : webSocketMap.keySet()) {
            try {
                webSocketMap.get(item).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("对话错误:" + this.ConversionId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 向客户端发送消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 通过userId向客户端发送消息
     */
    public void sendMessageByUserId(Long ConversionId, String message) throws IOException {
        logger.info("服务端发送消息到{},消息:{}", ConversionId, message);
        if (StrUtil.isNotBlank(ConversionId.toString()) && webSocketMap.containsKey(ConversionId.toString())) {
            webSocketMap.get(ConversionId.toString()).sendMessage(message);
        } else {
            logger.error("{}不在线", ConversionId);
        }

    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) {
        for (String item : webSocketMap.keySet()) {
            try {
                webSocketMap.get(item).sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

}
  • 在本项目中通过对话id标识用户的每次与cahtgpt的交互,并且将该对话下的所有内容保存在数据库中实现了对话的长久保存
gitee地址:

https://gitee.com/li-manxiang/chatgptservice.git文章来源地址https://www.toymoban.com/news/detail-593349.html

到了这里,关于java如何对接cahtgpt API(简单记录)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java RabbitMQ API 对接说明

    最近研发的物联网底层框架使用了RabbitMQ作为消息队列,如果监控消息队列对其通道是否出现阻塞能够及时获知与让管理员收到预警并及时处理,这里我们会采用RabbitMQ的rabbitmq_management插件。利用其提供的API进行获取信息,从而实现队列监控的目标。 如何安装RabbitMQ可以参考

    2024年02月09日
    浏览(43)
  • 记淘宝客、多多客api开发系列。一、淘宝联盟淘宝客api对接

    现在市面上较多、也较赚钱的就是开群拉人,然后在群里发高佣商品链接,群员下单后就可获得佣金,由于是淘宝客相对主动(类似行商),潜伏在他们群里,看到效果还不错。 但背后付出成本也不小,群要提防被封、防止群里有人捣乱、打广告的混入、需要买软件、开企业

    2024年02月09日
    浏览(35)
  • java对接阿里云通义千问API

    前提条件 1.已经获取申请名额,开通服务并获得API-KEY:开通DashScope并创建API-KEY。 2.maven安装对应的jar包组件 3.java代码调用接口 返回结果

    2024年02月22日
    浏览(40)
  • Java对接kafka简单示例

    Java可以使用Apache Kafka提供的kafka-clients库来对接Kafka。下面是一个简单的示例代码,展示了如何使用Java对接Kafka并发送和接收消息: 首先,确保已经在项目中添加了kafka-clients库的依赖。 以上代码演示了如何使用Kafka的生产者将消息发送到指定的topic,以及如何使用消费者从指

    2024年04月28日
    浏览(20)
  • java对接Prometheus的简单示例

    Prometheus是由CNCF(Cloud Native Computing Foundation)维护的开源监控和警报系统。它最初由SoundCloud开发,并于2012年发布。Prometheus旨在帮助开发人员和运维团队监控和管理大规模分布式系统的性能和健康状态。 Prometheus具有以下特点: 多维度数据模型:Prometheus采用一种灵活的数据模

    2024年02月06日
    浏览(26)
  • java对接微信支付api3心得(小白易懂)

            公司做的项目中,需要支付功能,因为做的微信小程序项目,所以直接就用微信支付了,以前我也对接过微信支付,但以前没有java的sdk,并且还是用的xml报文,我们还得解析xml才行,所以麻烦的很,这次对接突然发现,微信已经提供了好多中语言的sdk,其中也包

    2024年02月03日
    浏览(36)
  • 【Node.js实战】一文带你开发博客项目(API 对接 MySQL)

    个人简介 👀 个人主页: 前端杂货铺 🙋‍♂️ 学习方向: 主攻前端方向,也会涉及到服务端 📃 个人状态: 在校大学生一枚,已拿多个前端 offer(秋招) 🚀 未来打算: 为中国的工业软件事业效力n年 🥇 推荐学习:🍍前端面试宝典 🍉Vue2 🍋Vue3 🍓Vue2Vue3项目实战 🥝

    2024年02月02日
    浏览(49)
  • UG\NX二次开发 使用录制功能录制操作记录时,如何设置默认的开发语言?

    文章作者:里海 来源网站:王牌飞行员_里海_里海NX二次开发3000例,CC++,Qt-CSDN博客 NX二次开发使用BlockUI设计对话框时,如何设置默认的代码语言?   依次打开“文件”-“实用工具”-“用户默认设置”-“用户界面”-“操作记录”-“C++”。       

    2024年02月11日
    浏览(25)
  • weixin-java-pay对接微信V3支付记录

    https://github.com/binarywang/weixin-java-pay-demo 这个demo里, 没有v3版本的配置, 这里记录一下 v3支付, 相对之前的版本来说, 更为安全, 也相对繁琐一些, 而且请求和响应都使用了json格式的数据 1. 配置 发起支付所需的配置有三个证书文件, 在商户后台申请 apiclient_cert.p12 apiclient_key.pem ap

    2024年02月11日
    浏览(37)
  • 跨境电商无货源如何实现自动化对接1688货源商品上架?1688商品采集API来帮你

    阿里巴巴集团旗下的B2B电子商务网站,提供海量优质商品,为采购商和供应商提供交流、合作、采购等服务,是很多没有货源优势的电商卖家首选的货源途径,也是国内最大、货源种类最齐全的货源网站。 不少做跨境电商无货源的朋友都想要直接从1688源头厂家拿货,实现自

    2024年02月21日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包