Langchaine4j 流式输出 (6)

06-02 1053阅读

Langchaine4j 流式输出

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

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

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

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

流式输出

添加流式输出依赖


    org.springframework.boot
    spring-boot-starter-webflux


    dev.langchain4j
    langchain4j-reactor

使用流式输出模型

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 chat( String userMessage);
}

测试流式输出

  • 单元测试流式输出
    @SpringBootTest
    public class StreamModelTest {
        @Resource
        private StreamAssistant streamAssistant;
        @Test
        public void testStreamModel() throws InterruptedException {
            Flux 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();
        }
    }
    

    Langchaine4j 流式输出 (6)

    • 接口流式测试

      创建对外接口:

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

      Langchaine4j 流式输出 (6)

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码