feat: 实现伪流式接口,实时展示 LLM 执行步骤
- 新增 StreamingStepAdvisor 捕获每个执行步骤(工具调用、响应等) - 在 ChatService 中实现 chatStreamWithTools 方法 - 使用 SSE 实时推送执行步骤到前端 - 新增 /api/chat/stream-with-tools 接口 - 创建测试页面 stream-test.html 展示实时步骤 功能特性: - 实时显示用户消息 - 实时显示工具调用(工具名称、参数) - 实时显示工具响应 - 实时显示 AI 文本响应 - 支持错误处理和显示 访问地址:http://localhost:8080/stream-test.html Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
85b3130514
commit
0c5655af5b
4 files changed
+635
No files matched your search
@@ -0,0 +1,138 @@
|
||||
package org.springaicommunity.skills;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClientRequest;
|
||||
import org.springframework.ai.chat.client.ChatClientResponse;
|
||||
import org.springframework.ai.chat.client.advisor.api.AdvisorChain;
|
||||
import org.springframework.ai.chat.client.advisor.api.BaseAdvisor;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
|
||||
import reactor.core.publisher.Sinks;
|
||||
|
||||
/**
|
||||
* 流式步骤 Advisor - 捕获 LLM 执行的每个步骤并通过 SSE 发送
|
||||
*/
|
||||
public class StreamingStepAdvisor implements BaseAdvisor {
|
||||
|
||||
private final int order;
|
||||
private final Sinks.Many<Map<String, Object>> sink;
|
||||
|
||||
public StreamingStepAdvisor(int order, Sinks.Many<Map<String, Object>> sink) {
|
||||
this.order = order;
|
||||
this.sink = sink;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return this.order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
|
||||
// 发送用户消息事件
|
||||
var lastMessage = chatClientRequest.prompt().getInstructions()
|
||||
.get(chatClientRequest.prompt().getInstructions().size() - 1);
|
||||
|
||||
if (lastMessage.getMessageType() == org.springframework.ai.chat.messages.MessageType.USER) {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("type", "user_message");
|
||||
event.put("content", lastMessage.getText());
|
||||
emitEvent(event);
|
||||
}
|
||||
|
||||
return chatClientRequest;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
|
||||
if (chatClientResponse.chatResponse() == null || chatClientResponse.chatResponse().getResults() == null) {
|
||||
return chatClientResponse;
|
||||
}
|
||||
|
||||
for (var generation : chatClientResponse.chatResponse().getResults()) {
|
||||
var message = generation.getOutput();
|
||||
|
||||
// 捕获工具调用
|
||||
if (message.getToolCalls() != null && !message.getToolCalls().isEmpty()) {
|
||||
for (var toolCall : message.getToolCalls()) {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("type", "tool_call");
|
||||
event.put("tool_name", toolCall.name());
|
||||
event.put("tool_id", toolCall.id());
|
||||
event.put("arguments", toolCall.arguments());
|
||||
emitEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
// 捕获工具响应
|
||||
if (message.getMessageType() == org.springframework.ai.chat.messages.MessageType.TOOL) {
|
||||
var toolResponseMessage = (org.springframework.ai.chat.messages.ToolResponseMessage) message;
|
||||
for (var toolResponse : toolResponseMessage.getResponses()) {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("type", "tool_response");
|
||||
event.put("tool_name", toolResponse.name());
|
||||
event.put("tool_id", toolResponse.id());
|
||||
event.put("response", truncate(toolResponse.responseData(), 500));
|
||||
emitEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
// 捕获 AI 文本响应
|
||||
if (message instanceof AssistantMessage && message.getText() != null && !message.getText().isEmpty()) {
|
||||
// 只在没有工具调用时发送文本(避免重复)
|
||||
if (message.getToolCalls() == null || message.getToolCalls().isEmpty()) {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("type", "assistant_message");
|
||||
event.put("content", message.getText());
|
||||
emitEvent(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return chatClientResponse;
|
||||
}
|
||||
|
||||
private void emitEvent(Map<String, Object> event) {
|
||||
try {
|
||||
sink.tryEmitNext(event);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to emit event: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String truncate(String text, int maxLength) {
|
||||
if (text == null) return "";
|
||||
if (text.length() <= maxLength) return text;
|
||||
return text.substring(0, maxLength) + "...";
|
||||
}
|
||||
|
||||
public static Builder builder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
private int order = 0;
|
||||
private Sinks.Many<Map<String, Object>> sink;
|
||||
|
||||
public Builder order(int order) {
|
||||
this.order = order;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder sink(Sinks.Many<Map<String, Object>> sink) {
|
||||
this.sink = sink;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StreamingStepAdvisor build() {
|
||||
if (sink == null) {
|
||||
throw new IllegalStateException("Sink must be provided");
|
||||
}
|
||||
return new StreamingStepAdvisor(this.order, this.sink);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,17 @@ public class ChatController {
|
||||
return chatService.chatStream(finalConversationId, request.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 伪流式聊天接口(支持工具调用)- 实时返回每个执行步骤
|
||||
*/
|
||||
@PostMapping(value = "/stream-with-tools", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public Flux<String> chatStreamWithTools(
|
||||
@RequestParam(required = false) String conversationId,
|
||||
@RequestBody ChatRequest request) {
|
||||
String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString();
|
||||
return chatService.chatStreamWithTools(finalConversationId, request.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 非流式聊天接口(用于测试)
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.springaicommunity.skills.service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.ai.chat.memory.ChatMemory;
|
||||
@@ -10,21 +11,25 @@ import org.springframework.stereotype.Service;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Sinks;
|
||||
|
||||
@Service
|
||||
public class ChatService {
|
||||
|
||||
private final ChatClient streamChatClient; // 流式用(不支持工具)
|
||||
private final ChatClient chatClient; // 非流式用(支持工具)
|
||||
private final ChatClient.Builder chatClientBuilder; // 用于创建带自定义 Advisor 的客户端
|
||||
private final ChatMemory chatMemory;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ChatService(
|
||||
@Qualifier("streamChatClient") ChatClient streamChatClient,
|
||||
@Qualifier("chatClient") ChatClient chatClient,
|
||||
@Qualifier("chatClientBuilder") ChatClient.Builder chatClientBuilder,
|
||||
ChatMemory chatMemory) {
|
||||
this.streamChatClient = streamChatClient;
|
||||
this.chatClient = chatClient;
|
||||
this.chatClientBuilder = chatClientBuilder;
|
||||
this.chatMemory = chatMemory;
|
||||
this.objectMapper = new ObjectMapper();
|
||||
}
|
||||
@@ -41,6 +46,67 @@ public class ChatService {
|
||||
.map(this::mapToSSE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 伪流式聊天(支持工具调用)- 实时返回每个执行步骤
|
||||
*/
|
||||
public Flux<String> chatStreamWithTools(String conversationId, String userMessage) {
|
||||
// 创建一个 Sink 用于发送事件
|
||||
Sinks.Many<Map<String, Object>> sink = Sinks.many().multicast().onBackpressureBuffer();
|
||||
|
||||
// 在后台线程执行聊天
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
// 创建带有 StreamingStepAdvisor 的临时客户端
|
||||
ChatClient tempClient = chatClientBuilder
|
||||
.defaultAdvisors(
|
||||
org.springaicommunity.skills.StreamingStepAdvisor.builder()
|
||||
.order(-10) // 确保最先执行
|
||||
.sink(sink)
|
||||
.build(),
|
||||
org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor.builder(chatMemory).build()
|
||||
)
|
||||
.build();
|
||||
|
||||
// 执行聊天
|
||||
String content = tempClient.prompt()
|
||||
.user(userMessage)
|
||||
.advisors(a -> a.param("conversation_id", conversationId))
|
||||
.call()
|
||||
.content();
|
||||
|
||||
// 发送最终响应
|
||||
Map<String, Object> finalEvent = Map.of(
|
||||
"type", "final_response",
|
||||
"content", content
|
||||
);
|
||||
sink.tryEmitNext(finalEvent);
|
||||
|
||||
// 完成流
|
||||
sink.tryEmitComplete();
|
||||
|
||||
} catch (Exception e) {
|
||||
Map<String, Object> errorEvent = Map.of(
|
||||
"type", "error",
|
||||
"message", e.getMessage()
|
||||
);
|
||||
sink.tryEmitNext(errorEvent);
|
||||
sink.tryEmitError(e);
|
||||
}
|
||||
});
|
||||
|
||||
// 将事件转换为 SSE 格式
|
||||
return sink.asFlux()
|
||||
.map(event -> {
|
||||
try {
|
||||
String eventType = (String) event.get("type");
|
||||
String data = objectMapper.writeValueAsString(event);
|
||||
return formatSSE(eventType, data);
|
||||
} catch (Exception e) {
|
||||
return formatSSE("error", "{\"message\": \"" + e.getMessage() + "\"}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 非流式聊天(支持工具调用)
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user