feat(dashscope): 实现流式响应接口并返回AIResponse对象

- 新增AIResponse模型类用于封装流式响应内容- 修改DashScopeController以支持流式输出
- 将原有的chat方法改为generateStream方法
- 使用Prompt构建提示词并获取流式响应- 映射chatResponse到AIResponse对象- 添加@Slf4j注解以支持日志记录- 引入必要的Spring AI相关类和Lombok注解
This commit is contained in:
2025-10-22 22:40:55 +08:00
parent 2f9923977a
commit f8ff5808e5
2 changed files with 36 additions and 7 deletions

View File

@@ -1,13 +1,19 @@
package com.hanserwei.snailsai.controller;
import com.hanserwei.snailsai.model.AIResponse;
import com.hanserwei.snailsai.model.ChatMessageDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
@Slf4j
@RequestMapping("/dashscope")
@RestController
@CrossOrigin
@@ -16,12 +22,20 @@ public class DashScopeController {
@Resource
private ChatClient dashScopeChatClient;
@PostMapping(value = "/chat",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> chat(@RequestBody ChatMessageDTO chatMessageDTO) {
return dashScopeChatClient.prompt()
.user(chatMessageDTO.getMessage())
.advisors(e-> e.param(ChatMemory.CONVERSATION_ID,chatMessageDTO.getConversionId()))
.stream()
.content();
@PostMapping(value = "/generateStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<AIResponse> generateStream(@RequestBody ChatMessageDTO chatMessageDTO) {
// 构建提示词
Prompt prompt = new Prompt(new UserMessage(chatMessageDTO.getMessage()));
// 流式输出
return dashScopeChatClient.prompt(prompt)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatMessageDTO.getConversionId()))
.stream() // 流式输出
.chatResponse()
.mapNotNull(chatResponse -> {
Generation generation = chatResponse.getResult();
String text = generation.getOutput().getText();
return AIResponse.builder().v(text).build();
});
}
}

View File

@@ -0,0 +1,15 @@
package com.hanserwei.snailsai.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AIResponse {
// 流式响应内容
private String v;
}