diff --git a/docs/伪流式接口使用指南.md b/docs/伪流式接口使用指南.md new file mode 100644 index 0000000..c961068 --- /dev/null +++ b/docs/伪流式接口使用指南.md @@ -0,0 +1,547 @@ +# 伪流式接口使用指南 + +## 概述 + +伪流式接口通过 Server-Sent Events (SSE) 实时推送 LLM 的每个执行步骤,让用户能够看到 Agent 的完整工作过程,包括工具调用、工具响应、AI 思考等。 + +## 功能特性 + +### 实时步骤展示 + +- ✅ **用户消息**:显示用户输入 +- ✅ **工具调用**:显示调用的工具名称和参数 +- ✅ **工具响应**:显示工具执行结果 +- ✅ **AI 响应**:显示 AI 的文本回复 +- ✅ **错误处理**:显示执行过程中的错误 + +### 与传统流式的区别 + +| 特性 | 传统流式 | 伪流式(本实现) | +|------|---------|-----------------| +| 工具调用支持 | ❌ 不支持 | ✅ 完全支持 | +| 实时步骤展示 | ❌ 仅文本 | ✅ 所有步骤 | +| 工具调用可见 | ❌ 不可见 | ✅ 实时可见 | +| 响应方式 | 逐字符流式 | 按步骤流式 | +| 适用场景 | 简单对话 | 复杂任务 | + +## 技术架构 + +### 1. StreamingStepAdvisor + +核心组件,负责捕获 LLM 执行的每个步骤。 + +```java +public class StreamingStepAdvisor implements BaseAdvisor { + private final Sinks.Many> sink; + + @Override + public ChatClientResponse after(ChatClientResponse response, AdvisorChain chain) { + // 捕获工具调用 + if (message.getToolCalls() != null) { + for (var toolCall : message.getToolCalls()) { + Map event = Map.of( + "type", "tool_call", + "tool_name", toolCall.name(), + "arguments", toolCall.arguments() + ); + sink.tryEmitNext(event); + } + } + + // 捕获工具响应 + // 捕获 AI 文本响应 + // ... + } +} +``` + +**工作原理**: +1. 在 `after()` 方法中拦截每次 LLM 响应 +2. 解析响应中的工具调用、工具响应、文本等 +3. 通过 `Sinks.Many` 发送事件到前端 + +### 2. ChatService.chatStreamWithTools() + +创建临时 ChatClient 并执行聊天。 + +```java +public Flux chatStreamWithTools(String conversationId, String userMessage) { + // 创建 Sink + Sinks.Many> sink = Sinks.many().multicast().onBackpressureBuffer(); + + // 后台执行聊天 + CompletableFuture.runAsync(() -> { + // 创建带 StreamingStepAdvisor 的临时客户端 + ChatClient tempClient = chatClientBuilder + .defaultAdvisors( + StreamingStepAdvisor.builder() + .order(-10) + .sink(sink) + .build() + ) + .build(); + + // 执行聊天 + String content = tempClient.prompt() + .user(userMessage) + .call() + .content(); + + // 发送最终响应 + sink.tryEmitNext(Map.of("type", "final_response", "content", content)); + sink.tryEmitComplete(); + }); + + // 转换为 SSE 格式 + return sink.asFlux().map(event -> formatSSE(event)); +} +``` + +**关键点**: +- 使用 `CompletableFuture.runAsync()` 在后台执行 +- 通过 `Sinks.Many` 实现事件流 +- 每个步骤完成后立即发送事件 + +### 3. SSE 事件格式 + +``` +event: tool_call +data: {"type":"tool_call","tool_name":"get_customer_risk_cost","arguments":"{\"company_name\":\"测试企业\"}"} + +event: tool_response +data: {"type":"tool_response","tool_name":"get_customer_risk_cost","response":"测试企业的风险成本率为 2.15%"} + +event: final_response +data: {"type":"final_response","content":"根据查询结果,测试企业的风险成本率为 2.15%"} +``` + +## API 使用 + +### 端点 + +``` +POST /api/chat/stream-with-tools?conversationId={id} +Content-Type: application/json +Accept: text/event-stream +``` + +### 请求示例 + +```javascript +const response = await fetch('/api/chat/stream-with-tools?conversationId=xxx', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + message: '请帮我为"测试企业"进行定价' + }) +}); + +const reader = response.body.getReader(); +const decoder = new TextDecoder(); + +while (true) { + const { done, value } = await reader.read(); + if (done) break; + + const text = decoder.decode(value); + // 解析 SSE 事件 + parseSSE(text); +} +``` + +### 事件类型 + +| 事件类型 | 说明 | 数据字段 | +|---------|------|---------| +| `user_message` | 用户消息 | `content` | +| `tool_call` | 工具调用 | `tool_name`, `tool_id`, `arguments` | +| `tool_response` | 工具响应 | `tool_name`, `tool_id`, `response` | +| `assistant_message` | AI 文本响应 | `content` | +| `final_response` | 最终响应 | `content` | +| `error` | 错误 | `message` | + +## 前端集成 + +### 完整示例 + +访问测试页面:**http://localhost:8080/stream-test.html** + +### 核心代码 + +```javascript +async function sendMessage(message) { + const response = await fetch(`/api/chat/stream-with-tools?conversationId=${conversationId}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message }) + }); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n\n'); + buffer = lines.pop(); + + for (const line of lines) { + if (line.startsWith('event:')) { + const eventMatch = line.match(/event: (\w+)/); + const dataMatch = line.match(/data: (.+)/); + + if (eventMatch && dataMatch) { + const eventType = eventMatch[1]; + const data = JSON.parse(dataMatch[1]); + + // 根据事件类型处理 + handleEvent(eventType, data); + } + } + } + } +} + +function handleEvent(eventType, data) { + switch(eventType) { + case 'tool_call': + displayToolCall(data.tool_name, data.arguments); + break; + case 'tool_response': + displayToolResponse(data.tool_name, data.response); + break; + case 'assistant_message': + displayAssistantMessage(data.content); + break; + case 'final_response': + displayFinalResponse(data.content); + break; + case 'error': + displayError(data.message); + break; + } +} +``` + +## 使用场景 + +### 场景 1:复杂定价流程 + +**用户输入**: +``` +请帮我为"深圳某某科技有限公司"执行完整的定价流程 +``` + +**实时步骤展示**: +``` +🔧 调用工具: Skill + 参数: {"command":"客户定价","input":"深圳某某科技有限公司"} + +✅ 工具响应: Skill + 正在执行客户评级... + +🔧 调用工具: get_customer_risk_cost + 参数: {"company_name":"深圳某某科技有限公司"} + +✅ 工具响应: get_customer_risk_cost + 风险成本率为 1.85% + +🔧 调用工具: Skill + 参数: {"command":"定价方法选择",...} + +✅ 工具响应: Skill + 选择历史行为定价法 + +💬 AI 响应 + 根据分析,建议利率为 4.2% +``` + +### 场景 2:TodoWrite 任务管理 + +**用户输入**: +``` +分析最近 3 个月的定价数据,找出异常客户。使用 TodoWrite。 +``` + +**实时步骤展示**: +``` +🔧 调用工具: TodoWrite + 参数: {"todos":[{"content":"读取数据","status":"pending"},...]} + +📋 Progress: 0/4 tasks completed (0%) + [ ] 读取最近 3 个月的定价数据 + [ ] 分析数据找出异常客户 + [ ] 生成调整建议 + [ ] 保存报告 + +🔧 调用工具: FileSystemTools + 参数: {"operation":"read","path":"data/pricing.json"} + +✅ 工具响应: FileSystemTools + 成功读取 150 条记录 + +🔧 调用工具: TodoWrite + 参数: {"todos":[{"content":"读取数据","status":"completed"},...]} + +📋 Progress: 1/4 tasks completed (25%) + [✓] 读取最近 3 个月的定价数据 + [→] 分析数据找出异常客户 + [ ] 生成调整建议 + [ ] 保存报告 + +[继续执行...] +``` + +### 场景 3:多工具协作 + +**用户输入**: +``` +获取"测试企业"的风险成本,然后基于这个数据进行定价 +``` + +**实时步骤展示**: +``` +🔧 调用工具: get_customer_risk_cost + 参数: {"company_name":"测试企业"} + +✅ 工具响应: get_customer_risk_cost + 风险成本率为 2.15% + +💬 AI 响应 + 已获取风险成本率 2.15%,现在开始定价... + +🔧 调用工具: Skill + 参数: {"command":"客户定价","risk_cost":"2.15%"} + +✅ 工具响应: Skill + 定价完成,建议利率 4.5% + +💬 AI 响应 + 根据风险成本率 2.15%,建议利率为 4.5% +``` + +## 性能优化 + +### 1. 背压处理 + +使用 `Sinks.many().multicast().onBackpressureBuffer()` 处理背压: + +```java +Sinks.Many> sink = + Sinks.many().multicast().onBackpressureBuffer(); +``` + +### 2. 响应截断 + +对于过长的工具响应,自动截断: + +```java +private String truncate(String text, int maxLength) { + if (text == null) return ""; + if (text.length() <= maxLength) return text; + return text.substring(0, maxLength) + "..."; +} +``` + +### 3. 异步执行 + +使用 `CompletableFuture.runAsync()` 避免阻塞: + +```java +CompletableFuture.runAsync(() -> { + // 执行聊天 + String content = tempClient.prompt().user(userMessage).call().content(); + sink.tryEmitComplete(); +}); +``` + +## 故障排查 + +### 问题 1:事件未收到 + +**症状**:前端无法接收 SSE 事件 + +**检查清单**: +1. ✅ 确认请求头 `Accept: text/event-stream` +2. ✅ 检查浏览器控制台是否有错误 +3. ✅ 查看服务器日志 + +**解决方案**: +```javascript +// 确保正确设置 Accept 头 +const response = await fetch(url, { + headers: { + 'Accept': 'text/event-stream' + } +}); +``` + +### 问题 2:事件顺序混乱 + +**原因**:多个工具并发调用 + +**解决方案**: +- StreamingStepAdvisor 的 `order` 设置为 `-10`,确保最先执行 +- 使用 `multicast()` 确保事件顺序 + +### 问题 3:连接中断 + +**症状**:SSE 连接意外断开 + +**解决方案**: +```javascript +// 添加重连逻辑 +function connectSSE() { + const eventSource = new EventSource(url); + + eventSource.onerror = () => { + eventSource.close(); + setTimeout(connectSSE, 3000); // 3秒后重连 + }; +} +``` + +## 与现有接口对比 + +### /api/chat/chat(非流式) + +``` +优点: +- 简单直接 +- 一次性返回完整结果 + +缺点: +- 无法看到执行过程 +- 长时间等待无反馈 +``` + +### /api/chat/stream(传统流式) + +``` +优点: +- 逐字符流式输出 +- 响应快 + +缺点: +- 不支持工具调用 +- 无法看到工具执行过程 +``` + +### /api/chat/stream-with-tools(伪流式)✨ + +``` +优点: +- 完全支持工具调用 +- 实时展示每个执行步骤 +- 用户体验最佳 + +缺点: +- 实现复杂度较高 +- 需要前端配合解析事件 +``` + +## 最佳实践 + +### 1. 前端展示 + +**推荐方式**: +- 使用不同颜色区分不同类型的步骤 +- 工具调用:橙色 +- 工具响应:绿色 +- AI 响应:蓝色 +- 错误:红色 + +**示例 CSS**: +```css +.step.tool-call { + background: #fff3e0; + border-left: 4px solid #ff9800; +} + +.step.tool-response { + background: #e8f5e9; + border-left: 4px solid #4caf50; +} +``` + +### 2. 错误处理 + +**捕获所有错误**: +```java +try { + String content = tempClient.prompt().user(userMessage).call().content(); + sink.tryEmitNext(Map.of("type", "final_response", "content", content)); +} catch (Exception e) { + sink.tryEmitNext(Map.of("type", "error", "message", e.getMessage())); +} finally { + sink.tryEmitComplete(); +} +``` + +### 3. 超时处理 + +**设置合理的超时**: +```java +CompletableFuture.runAsync(() -> { + // 执行聊天 +}, executor) +.orTimeout(60, TimeUnit.SECONDS) // 60秒超时 +.exceptionally(ex -> { + sink.tryEmitNext(Map.of("type", "error", "message", "请求超时")); + return null; +}); +``` + +## 扩展功能 + +### 1. 添加进度百分比 + +```java +Map event = Map.of( + "type", "progress", + "current", currentStep, + "total", totalSteps, + "percentage", (currentStep * 100 / totalSteps) +); +sink.tryEmitNext(event); +``` + +### 2. 添加时间戳 + +```java +Map event = Map.of( + "type", "tool_call", + "tool_name", toolCall.name(), + "timestamp", System.currentTimeMillis() +); +``` + +### 3. 添加执行时长 + +```java +long startTime = System.currentTimeMillis(); +// 执行工具 +long duration = System.currentTimeMillis() - startTime; + +Map event = Map.of( + "type", "tool_response", + "duration_ms", duration +); +``` + +## 参考资源 + +- [Server-Sent Events 规范](https://html.spec.whatwg.org/multipage/server-sent-events.html) +- [Project Reactor 文档](https://projectreactor.io/docs/core/release/reference/) +- [Spring WebFlux SSE](https://docs.spring.io/spring-framework/reference/web/webflux/reactive-spring.html#webflux-sse) + +--- + +**版本**: 1.0.0 +**更新日期**: 2026-01-30 +**测试页面**: http://localhost:8080/stream-test.html