当前位置: 首页 > news >正文

Langchaine4j 流式输出 (6)

Langchaine4j 流式输出

大模型的流式输出是指大模型在生成文本或其他类型的数据时,不是等到整个生成过程完成后再一次性

返回所有内容,而是生成一部分就立即发送一部分给用户或下游系统,以逐步、逐块的方式返回结果。

这样,用户就不需要等待整个文本生成完成再看到结果。通过这种方式可以改善用户体验,因为用户不

需要等待太长时间,几乎可以立即开始阅读响应。

流式输出

添加流式输出依赖

<!--流式输出-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency><groupId>dev.langchain4j</groupId><artifactId>langchain4j-reactor</artifactId>
</dependency>

使用流式输出模型

langchain4j:# 接入阿里百炼平台community:dashscope:streaming-chat-model:api-key: ${ALI_BAILIAN_TOKEN}model-name: qwen-plus

创建流式Assistant

@AiService(wiringMode = AiServiceWiringMode.EXPLICIT,streamingChatModel = "qwenStreamingChatModel", // 这里注入 千问流式模型chatMemory = "chatMemory")
public interface StreamAssistant {// 使用WebFlux接受流式模型返回Flux<String> chat( String userMessage);}

测试流式输出

  • 单元测试流式输出
@SpringBootTest
public class StreamModelTest {@Resourceprivate StreamAssistant streamAssistant;@Testpublic void testStreamModel() throws InterruptedException {Flux<String> responseFlux = streamAssistant.chat("1+2等于几,322233222345的平方根是多少?");CountDownLatch latch = new CountDownLatch(1);responseFlux.doOnSubscribe(sub -> System.out.println("Subscribed to flux")).subscribe(chunk -> System.out.println("Received: " + chunk),throwable -> {System.err.println("Error occurred: " + throwable.getMessage());latch.countDown();},() -> {System.out.println("Completed");latch.countDown();});latch.await();}
}

PixPin_2025-06-01_15-07-16

  • 接口流式测试

    创建对外接口:

    @RestController
    @RequestMapping("/stream")
    public class StreamController {@Resourceprivate StreamAssistant streamAssistant;@Operation(summary = "对话")@GetMapping(value = "/chat", produces = "text/stream;charset=utf-8") // 设置响应类型为流式文本,并指定字符集为UTF-8public Flux<String> chat() {return streamAssistant.chat("1+2等于几,322233222345的平方根是多少?");}
    }
    

    chrome_stream

相关文章:

  • Vim 支持多种编程语言编辑器
  • NLP学习路线图(十五):TF-IDF(词频-逆文档频率)
  • Python Django完整教程与代码示例
  • 计算机网络(5)——数据链路层
  • 超标量处理器设计6-指令解码
  • Chorme如何对于youtube视频进行画中画背景播放?
  • wordpress免费主题网站
  • 利用 Python 爬虫获取淘宝商品详情
  • Java数据结构——八大排序
  • 04.MySQL数据类型详解
  • 网络攻防技术一:绪论
  • 深入解析Vue.js:构建现代Web应用的高效之道
  • 机电的焊接技术
  • MQTT入门实战宝典:从零起步掌握物联网核心通信协议
  • 如何学习开关电源?从“大”到“小”学习开关电源...
  • 第6节 Node.js 回调函数
  • SSL/TLS 协议详解:安全通信的基石
  • VSCODE的终端无法执行npm命令
  • opencv使用经典bug
  • Hive SQL优化实践:提升大数据处理效率的关键策略
  • 深圳企业宣传片制作/长沙快速排名优化
  • 建立互联网公司网站/线上推广平台都有哪些
  • 趴比库的网站是谁建设的/关键词抓取工具都有哪些
  • 深圳优化网站公司/外链网址
  • 做网站分几步/独立站seo
  • 网站速度打开慢的原因/今天的新闻大事10条