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();}
}
-
接口流式測試
創建對外接口:
@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的平方根是多少?");} }