Langchaine4j 流式输出 (6)

[复制链接]
发表于 2025-6-22 00:39:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Langchaine4j 流式输出

大模型的流式输出是指大模型在生成文本或其他类型的数据时,不是等到整个生成过程完成后再一次性
返回所有内容,而是生成一部门就立即发送一部门给用户或卑鄙体系,以逐步、逐块的方式返回效果。
如许,用户就不须要等待整个文本生成完成再看到效果。通过这种方式可以改善用户体验,由于用户不
须要等待太长时间,几乎可以立即开始阅读响应。
流式输出

添加流式输出依靠

  1. <!--流式输出-->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-webflux</artifactId>
  5. </dependency>
  6. <dependency>
  7.     <groupId>dev.langchain4j</groupId>
  8.     <artifactId>langchain4j-reactor</artifactId>
  9. </dependency>
复制代码
利用流式输出模型

  1. langchain4j:
  2. # 接入阿里百炼平台
  3.   community:
  4.     dashscope:
  5.       streaming-chat-model:
  6.         api-key: ${ALI_BAILIAN_TOKEN}
  7.         model-name: qwen-plus
复制代码
创建流式Assistant

  1. @AiService(wiringMode = AiServiceWiringMode.EXPLICIT,
  2.         streamingChatModel = "qwenStreamingChatModel", // 这里注入 千问流式模型
  3.         chatMemory = "chatMemory")
  4. public interface StreamAssistant {
  5.         // 使用WebFlux接受流式模型返回
  6.     Flux<String> chat( String userMessage);
  7. }
复制代码
测试流式输出



  • 单位测试流式输出
  1. @SpringBootTest
  2. public class StreamModelTest {
  3.     @Resource
  4.     private StreamAssistant streamAssistant;
  5.     @Test
  6.     public void testStreamModel() throws InterruptedException {
  7.         Flux<String> responseFlux = streamAssistant.chat("1+2等于几,322233222345的平方根是多少?");
  8.         CountDownLatch latch = new CountDownLatch(1);
  9.         responseFlux
  10.                 .doOnSubscribe(sub -> System.out.println("Subscribed to flux"))
  11.                 .subscribe(
  12.                         chunk -> System.out.println("Received: " + chunk),
  13.                         throwable -> {
  14.                             System.err.println("Error occurred: " + throwable.getMessage());
  15.                             latch.countDown();
  16.                         },
  17.                         () -> {
  18.                             System.out.println("Completed");
  19.                             latch.countDown();
  20.                         }
  21.                 );
  22.         latch.await();
  23.     }
  24. }
复制代码



  • 接口流式测试
    创建对外接口:
    1. @RestController
    2. @RequestMapping("/stream")
    3. public class StreamController {
    4.     @Resource
    5.     private StreamAssistant streamAssistant;
    6.     @Operation(summary = "对话")
    7.     @GetMapping(value = "/chat", produces = "text/stream;charset=utf-8") // 设置响应类型为流式文本,并指定字符集为UTF-8
    8.     public Flux<String> chat() {
    9.         return streamAssistant.chat("1+2等于几,322233222345的平方根是多少?");
    10.     }
    11. }
    复制代码

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表