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

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

http://www.lryc.cn/news/2402402.html

相关文章:

  • Jenkins:自动化流水线的基石,开启 DevOps 新时代
  • 学习经验分享【40】目标检测热力图制作
  • C#里与嵌入式系统W5500网络通讯(3)
  • 用OpenNI2获取奥比中光Astra Pro输出的深度图(win,linux arm64 x64平台)
  • Unity VR/MR开发-VR设备与适用场景分析
  • Linux: network: switch:arp cache更新规则 [chatGPT]
  • Java网络编程API 1
  • Android协程学习
  • Angular报错:cann‘t bind to ngClass since it is‘t a known property of div
  • uniapp+vue3实现CK通信协议(基于jjc-tcpTools)
  • Python爬虫实战:研究urlparse库相关技术
  • 解锁FastAPI与MongoDB聚合管道的性能奥秘
  • 软件工程方法论:在确定性与不确定性的永恒之舞中寻找平衡
  • Unity中的MonoSingleton<T>与Singleton<T>
  • 怎么通过 jvmti 去 hook java 层函数
  • 兰亭妙微 | 医疗软件的界面设计能有多专业?
  • 前端原生构建交互式进度步骤组件(Progress Steps)
  • 如何给windos11 扩大C盘容量
  • 【基于阿里云搭建数据仓库(离线)】Data Studio创建资源与函数
  • Linux_T(Sticky Bit)粘滞位详解
  • web3-以太坊智能合约基础(理解智能合约Solidity)
  • 高敏感应用如何保护自身不被逆向?iOS 安全加固策略与工具组合实战(含 Ipa Guard 等)
  • 【C++项目】负载均衡在线OJ系统-2
  • GC1809:高性能24bit/192kHz音频接收芯片解析
  • 2025年06月05日Github流行趋势
  • flask功能使用总结和完整示例
  • AWS 亚马逊 S3存储桶直传 前端demo 复制即可使用
  • DAY 15 复习日
  • Vue Router 导航方法完全指南
  • MidJourney入门学习