SpringBoot中承接SSE流式输出的核心代码


AIGC人工智能
专栏收录该内容
10 篇文章0 订阅
订阅专栏
常用作对接AI大模型,AI大模型为了保证推理速度和用户体验,会进行sse流式返回。

一、引入依赖
<!-- okhttp依赖,okhttp对SSE流式输出的稳定性和速度最优 -->
        <dependency>
            <groupId>com.squareup.okhttp</groupId>
            <artifactId>okhttp</artifactId>
            <version>2.7.5</version>
        </dependency>
1
2
3
4
5
6
二、编写大模型的连接器
比如我要连接多个大模型,文心一言、智谱AI、以及公司内部的自有模型,就需要将连接器抽离出来进行单独编写。下面就是一个连接器的例子:

@Component
public class AppLLMChainClient {

    @Value("${ai.app.KnowledgeBase.url}")
    private String COMPLETION_ENDPOINT_ONE;
    private static Logger logger = LoggerFactory.getLogger(AppLLMChainClient.class);

    OkHttpClient client = new OkHttpClient();
    MediaType mediaType;
    Request.Builder requestBuilder;

    /**
     * 初始化连接器
     */
    @PostConstruct
    private void init() {
        //client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("xxx.xx.xx.x0", 9999)));
        client.setConnectTimeout(60, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
        mediaType = MediaType.parse("application/json; charset=utf-8");
        requestBuilder = new Request.Builder()
                .url(COMPLETION_ENDPOINT_ONE + "chat/chat")
                .header("Content-Type", "application/json; charset=utf-8")
                .header("Accept", "text/event-stream");
    }

    /**
     * 与LLM模型对话,通过LLMChain功能
     */
    public Response chatChat(AppLLMChainRequestBody query) throws ChatException {
        RequestBody bodyOk = RequestBody.create(mediaType, JSONObject.toJSONString(query));
        Request requestOk = requestBuilder.post(bodyOk).build();
        Call call = client.newCall(requestOk);
        Response response;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new ChatException("LLMChain 请求时IO异常: " + e.getMessage());
        }
        if (response.isSuccessful()) {
            return response;
        }
        try(ResponseBody body = response.body()) {
            throw new ChatException("LLMChain 请求异常, code: " + response.code() + "body: " + body.string());
        } catch (IOException e) {
            throw new ChatException("LLMChain 请求后IO异常: " + e.getMessage());
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
三、应用大模型LLM的核心处理器,SSE流式返回
public class AppLLMConverseHandleWrapper {

    public static AppLLMChainClient appLLMChainClient;

    private static final ExecutorService appLLMChainES = Executors.newFixedThreadPool(10);

    private final static Pattern contentPattern = Pattern.compile(AppConsts.SSE_RESULT_PREFIX2);

    private static final Logger log = LoggerFactory.getLogger(AppLLMConverseHandleWrapper.class);

    // 用于数据传输的 SseEmitter
    private final SseEmitter emitter = new SseEmitter(0L);

    // 对话上下文
    private List<AppLLMChainQAHistoryEntity> history;

    // 当前用户问题内容
    private String query;

    /**
     * 对话处理
     * @return SseEmitter
     */
    public SseEmitter handle() {
        if (!messageListCheck()) {
            return emitter;
        }
        doConverse();
        return emitter;
    }

    /**
     * 流式对话,异步的,在新的线程的
     */
    public SseEmitter doConverse() {
        appLLMChainES.execute(this::run);
        return emitter;
    }

    /**
     * 对话上下文检查
     * @return 是否通过
     */
    private boolean messageListCheck() {
        //限制会话次数
        if (history.size() > AppConsts.MSG_LIST_MAX) {
            sendData2Client(AppConsts.EVENT_ERROR, "上下文对话次数超限啦!");
            return false;
        }
        return true;
    }


    /**
     * 向客户端发送数据
     * @param event 事件类型
     * @param data 数据
     */
    private boolean sendData2Client(String event, String data) {
        try {
            emitter.send(SseEmitter.event().name(event).data(JSON.toJSONString(data)));
            return true;
        } catch (IOException e) {
            log.error("向客户端发送消息时出现异常");
            e.printStackTrace();
        }
        return false;
    }


    private void run() {
        AppLLMChainRequestBody chatRequestBody = new AppLLMChainRequestBody();
        chatRequestBody.setHistory(history);
        chatRequestBody.setQuery(query);
        Response chatResponse;
        try {
            chatResponse = appLLMChainClient.chatChat(chatRequestBody);
        } catch (ChatException e) {
            sendData2Client(AppConsts.EVENT_ERROR, "网络连接异常,请稍后重试");
            emitter.complete();
            e.printStackTrace();
            return;
        }
        try (ResponseBody responseBody = chatResponse.body();
             InputStream inputStream = responseBody.byteStream();
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            String content = null;
            //循环发送主体内容
            while ((line = bufferedReader.readLine()) != null) {
                if (StringUtils.hasLength(line)) {
                    /*log.info("data:{}", line);
                    Matcher matcher = contentPattern.matcher(line);
                    if (matcher.find()) {
                        log.info("进入data:{}", line);
                    }*/
                    if (!sendData2Client(AppConsts.EVENT_DATA, line)) {
                        break;
                    }
                }
            }
        } catch (IOException e) {
            log.error("ResponseBody读取错误");
            e.printStackTrace();
        } finally {
            emitter.complete();
        }
    }

    public AppLLMConverseHandleWrapper(){}
    public AppLLMConverseHandleWrapper(List<AppLLMChainQAHistoryEntity> history, String query) {
        this.history = history;
        this.query = query;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
四、将上方编写的各个大模型的连接器抽象成配置类并注册,方便拓展和统一维护
@Configuration
public class ConverseHandleConfig {

    @Autowired
    WYKnowledgeBase01Client wyKnowledgeBase01Client;
    @Autowired
    WYLLMClient wyllmClient;
    @Autowired
    AppKnowledgeBaseClient appKnowledgeBaseClient;
    @Autowired
    AppLLMChainClient appLLMChainClient;

    /**
     * 注册各个连接器
     */
    @PostConstruct
    private void init() {
        WYKnowledgeOneConverseHandleWrapper.wyKnowledgeBase01Client = this.wyKnowledgeBase01Client; //文心一言知识库01的连接器
        WYLLMConverseHandleWrapper.wyllmClient = this.wyllmClient; //文心一言LLM的连接器
        AppKnowledgeOneConverseHandleWrapper.appKnowledgeBaseClient = this.appKnowledgeBaseClient; //应用知识库连接器
        AppLLMConverseHandleWrapper.appLLMChainClient = this.appLLMChainClient;//应用大模型LLMChain连接器
    }


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
调用的话就像这样调用就可以啦:


给小伙伴补充一下前端的输出效果打印:


文章知识点与官方知识档案匹配,可进一步学习相关知识
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/qq_42969135/article/details/134595472

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot,可以通过使用Server-Sent Events(SSE)技术来实现流式输出SSE是一种基于HTTP的服务端推送技术,它允许服务器向客户端发送单向的数据流,这些数据可以是文本、JSON等数据格式。 下面是一个使用Spring Boot SSE实现流式输出的示例代码: 首先,在Spring Boot应用程序添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` 然后,创建一个RESTful控制器,该控制器使用SSE技术向客户端输出数据。以下是一个简单的控制器示例: ```java @RestController public class MyController { @GetMapping("/stream") public Flux<String> stream() { return Flux.interval(Duration.ofSeconds(1)) .map(seq -> "Stream - " + seq); } } ``` 在上面的示例,我们使用`@GetMapping`注解将一个路由绑定到`/stream`路径。当客户端连接到此路由时,控制器将使用`Flux`对象返回数据流。在这种情况下,我们使用`Flux.interval()`方法创建一个每秒发送一次消息的数据流。 最后,在客户端,可以使用JavaScript代码来订阅SSE事件并接收数据。以下是一个简单的JavaScript代码示例: ```javascript const source = new EventSource('/stream'); source.onmessage = function(event) { console.log(event.data); }; ``` 在上面的示例,我们使用`EventSource`对象来订阅`/stream`路径上的SSE事件。当事件被触发时,回调函数将被调用,并显示接收到的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值