文心一言的流式接口数据进行处理 增加属性

需求:需要对文心一言的流式接口数据进行处理 增加属性

复制代码
return ResponseEntity.ok()
                .header("Access-Control-Allow-Origin", "*")
                .contentType(org.springframework.http.MediaType.TEXT_EVENT_STREAM)
                .cacheControl(org.springframework.http.CacheControl.noCache())
                .body(outputStream -> {
                        try (Response response = client.newCall(request).execute();
                             ResponseBody responseBody = response.body();
                             InputStream inputStream = responseBody.byteStream()) {
                            if (!response.isSuccessful()) {
                                throw new IOException("Failed to fetch streaming data, HTTP error code: " + response.code());
                            }
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                /*outputStream.write(buffer, 0, bytesRead);
                                outputStream.flush();*/
                                String data = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                                String[] lines = data.split("\n");
                                for (String line : lines) {
                                    if (line.startsWith("data: ")) {
                                        // 记录流输出结果,用于后续持久化
                                        com.zbIntel.integration.wenxin.entity.ChatResponse bean =
                                                JSONUtil.parseObj(line.substring(6).getBytes(StandardCharsets.UTF_8))
                                                        .toBean(com.zbIntel.integration.wenxin.entity.ChatResponse.class);
                                        bean.setSessionId(req.getSessionId());

                                        // 序列化bean并发送
                                        String serializedBean = JSONUtil.toJsonStr(bean);
                                        outputStream.write(("data: " + serializedBean + "\n\n").getBytes(StandardCharsets.UTF_8));
                                        outputStream.flush();

                                        log.info("返回数据:{}", bean);
                                        String content = bean.getResult();
                                        if (bean.getIs_end()) {
                                            isEndflag.set(Boolean.TRUE);
                                        }
                                        // 记录流输出结果,用于后续持久化
                                        respContent.append(content);
                                    }
                                }
                            }
                        } catch (IOException e) {
                            log.error("Error during streaming data: ", e);
                            outputStream.write(("{" +
                                    "  \"error_code\": 112," +
                                    "  \"error_msg\": \"" + e.getMessage() + "\"" +
                                    "}").getBytes(StandardCharsets.UTF_8));
                            outputStream.flush();
                        }

                    if(isEndflag.get()) {
                        // 构造回复数据对象,持久化
                        String respContentStr = respContent.toString();
                        SessionChatRecordEntity replyRecord = new SessionChatRecordEntity(
                                finalAskRecord.getSessionId(), Role.ASSISTANT.name,
                                respContentStr, ChatGPTApi.getMessageTokenNum(respContentStr));
                        sessionChatRecordService.saveBatch(ImmutableList.of(finalAskRecord, replyRecord));

                        // 刷新缓存
                        chatService.refreshWindowRecordCache(finalAskRecord.getSessionId());
                    }
                }
        );

主要时这段:

// 序列化bean并发送

String serializedBean = JSONUtil.toJsonStr(bean);

outputStream.write(("data: " + serializedBean + "\n\n").getBytes(StandardCharsets.UTF_8));

outputStream.flush();

返回的结果:

增加了 sessionId的属性

相关推荐
周末也要写八哥4 分钟前
线程的生命周期之“守护“线程
java·开发语言·jvm
乐之者v5 分钟前
地图技术后端开发的知识点
java
亦暖筑序11 分钟前
Java 8老系统AI工具接入:API包装成受控工具,只读优先+权限拦截
java·人工智能·aigc·企业架构·mcp协议
砍材农夫12 分钟前
物联网实战:Spring Boot + Netty 搭建 MQTT 统一接入层
java·网络·spring boot·后端·物联网·spring
写代码的小阿帆13 分钟前
英语四六级证书审核(SpringBoot+Dify+RPA)
java·spring boot
redaijufeng14 分钟前
我在C++中深入理解了继承,收获颇丰
java·c++·算法
就叫_这个吧21 分钟前
HTML或JSP页面链接CSS,link标签没问题,但不显示样式问题解决
java·前端·css·html·intellij-idea·jsp
阿坤带你走近大数据26 分钟前
分别介绍下java主流的开发框架、设计模式与对应编程语言的高级特性
java·开发语言·设计模式
番茄去哪了34 分钟前
一篇文章讲懂SDN
java·spring
AC赳赳老秦39 分钟前
OpenClaw + 华为云自动化:批量管理云资源、生成月度云账单分析与成本优化报告
java·开发语言·javascript·人工智能·python·mysql·openclaw