@Value("${ai-api-key}")
private String apiKey;
@Resource
private Generation generation;
@SaIgnore
@GetMapping(value = "/send", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamAsk(String text) throws Exception {
Generation gen = new Generation();
// 创建用户消息对象
Message userMsg = Message
.builder()
.role(Role.USER.getValue())
.content(text)
.build();
// 创建QwenParam对象,设置参数
QwenParam param = QwenParam.builder()
.model(Generation.Models.QWEN_PLUS)
.messages(Arrays.asList(userMsg))
.resultFormat(QwenParam.ResultFormat.MESSAGE)
.topP(0.8)
.enableSearch(true)
.apiKey(apiKey)
// get streaming output incrementally
.incrementalOutput(false)
.build();
// 调用生成接口,获取Flowable对象
Flowable<GenerationResult> result = gen.streamCall(param);
// 将Flowable转换成Flux<ServerSentEvent<String>>并进行处理
return Flux.from(result)
.publishOn(Schedulers.boundedElastic())
// add delay between each event
// .delayElements(Duration.ofMillis(5))
.map(message -> {
String requestId = message.getRequestId();
System.out.println("request:"+requestId);
String output = message.getOutput().getChoices().get(0).getMessage().getContent();
System.out.println(output); // print the output
try {
Thread.sleep(10);
return ServerSentEvent.<String>builder()
.data(output)
.build();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
})
.concatWith(Flux.just(ServerSentEvent.<String>builder().comment("").build()))
.doOnError(e -> {
if (e instanceof NoApiKeyException) {
// 处理 NoApiKeyException
} else if (e instanceof InputRequiredException) {
// 处理 InputRequiredException
} else if (e instanceof ApiException) {
// 处理其他 ApiException
} else {
// 处理其他异常
}
});
}
我想通过接口的形式调用阿里的通义千问,本地这边就是一段一段的返回给前端,接口调用前端这边就建立了连接,但是到了服务器里面之后,前端调用接口,服务器也是一段一段的打印了出来,但是是全部打印出来之后,才发给前端,然后建立的连接.很奇怪!
如果您也遇到了这方面的问题并且有解决问题的思路,请帮帮我,好人一生平安!