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() + "\"}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 非流式聊天(支持工具调用)
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>伪流式聊天测试 - Spring AI Skills Demo</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||
width: 100%;
|
||||
max-width: 900px;
|
||||
height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
font-size: 24px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.header p {
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.chat-area {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 15px;
|
||||
animation: fadeIn 0.3s ease-in;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.message.user {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
display: inline-block;
|
||||
max-width: 70%;
|
||||
padding: 12px 16px;
|
||||
border-radius: 18px;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.message.user .message-content {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.message.assistant .message-content {
|
||||
background: white;
|
||||
color: #333;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.step {
|
||||
margin: 10px 0;
|
||||
padding: 10px;
|
||||
background: #e3f2fd;
|
||||
border-left: 4px solid #2196F3;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.step.tool-call {
|
||||
background: #fff3e0;
|
||||
border-left-color: #ff9800;
|
||||
}
|
||||
|
||||
.step.tool-response {
|
||||
background: #e8f5e9;
|
||||
border-left-color: #4caf50;
|
||||
}
|
||||
|
||||
.step.error {
|
||||
background: #ffebee;
|
||||
border-left-color: #f44336;
|
||||
}
|
||||
|
||||
.step-type {
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.step-type::before {
|
||||
content: '●';
|
||||
margin-right: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.step.tool-call .step-type::before {
|
||||
color: #ff9800;
|
||||
}
|
||||
|
||||
.step.tool-response .step-type::before {
|
||||
color: #4caf50;
|
||||
}
|
||||
|
||||
.step-content {
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 13px;
|
||||
color: #555;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.input-area {
|
||||
padding: 20px;
|
||||
background: white;
|
||||
border-top: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.input-container {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
#messageInput {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 25px;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.3s;
|
||||
}
|
||||
|
||||
#messageInput:focus {
|
||||
border-color: #667eea;
|
||||
}
|
||||
|
||||
#sendButton {
|
||||
padding: 12px 30px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 25px;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
|
||||
#sendButton:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
#sendButton:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.loading {
|
||||
display: inline-block;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 3px solid rgba(255, 255, 255, 0.3);
|
||||
border-radius: 50%;
|
||||
border-top-color: white;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: #f1f1f1;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #888;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #555;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>🤖 伪流式聊天测试</h1>
|
||||
<p>实时展示 LLM 的每个执行步骤(工具调用、响应等)</p>
|
||||
</div>
|
||||
|
||||
<div class="chat-area" id="chatArea">
|
||||
<div class="message assistant">
|
||||
<div class="message-content">
|
||||
你好!我是 AI 助手。我可以使用多种工具来帮助你,包括:<br>
|
||||
• 定价 Skills(客户评级、定价计算等)<br>
|
||||
• MCP 工具(获取风险成本)<br>
|
||||
• TodoWrite(任务管理)<br>
|
||||
• 文件操作和 Shell 命令<br><br>
|
||||
试试问我:"请帮我为某某公司进行定价"
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="input-area">
|
||||
<div class="input-container">
|
||||
<input type="text" id="messageInput" placeholder="输入消息..." />
|
||||
<button id="sendButton" onclick="sendMessage()">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const chatArea = document.getElementById('chatArea');
|
||||
const messageInput = document.getElementById('messageInput');
|
||||
const sendButton = document.getElementById('sendButton');
|
||||
let conversationId = generateUUID();
|
||||
let currentStepsContainer = null;
|
||||
|
||||
function generateUUID() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
||||
const r = Math.random() * 16 | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
function addMessage(content, isUser = false) {
|
||||
const messageDiv = document.createElement('div');
|
||||
messageDiv.className = `message ${isUser ? 'user' : 'assistant'}`;
|
||||
|
||||
const contentDiv = document.createElement('div');
|
||||
contentDiv.className = 'message-content';
|
||||
contentDiv.textContent = content;
|
||||
|
||||
messageDiv.appendChild(contentDiv);
|
||||
chatArea.appendChild(messageDiv);
|
||||
chatArea.scrollTop = chatArea.scrollHeight;
|
||||
|
||||
// 如果是助手消息,创建步骤容器
|
||||
if (!isUser) {
|
||||
currentStepsContainer = document.createElement('div');
|
||||
currentStepsContainer.style.marginLeft = '20px';
|
||||
chatArea.appendChild(currentStepsContainer);
|
||||
}
|
||||
}
|
||||
|
||||
function addStep(type, data) {
|
||||
if (!currentStepsContainer) return;
|
||||
|
||||
const stepDiv = document.createElement('div');
|
||||
stepDiv.className = `step ${type}`;
|
||||
|
||||
const typeDiv = document.createElement('div');
|
||||
typeDiv.className = 'step-type';
|
||||
|
||||
let typeText = '';
|
||||
let contentText = '';
|
||||
|
||||
switch(type) {
|
||||
case 'tool-call':
|
||||
typeText = `🔧 调用工具: ${data.tool_name}`;
|
||||
contentText = `参数: ${data.arguments}`;
|
||||
break;
|
||||
case 'tool-response':
|
||||
typeText = `✅ 工具响应: ${data.tool_name}`;
|
||||
contentText = data.response;
|
||||
break;
|
||||
case 'assistant-message':
|
||||
typeText = '💬 AI 响应';
|
||||
contentText = data.content;
|
||||
break;
|
||||
case 'error':
|
||||
typeText = '❌ 错误';
|
||||
contentText = data.message;
|
||||
break;
|
||||
}
|
||||
|
||||
typeDiv.textContent = typeText;
|
||||
stepDiv.appendChild(typeDiv);
|
||||
|
||||
if (contentText) {
|
||||
const contentDiv = document.createElement('div');
|
||||
contentDiv.className = 'step-content';
|
||||
contentDiv.textContent = contentText;
|
||||
stepDiv.appendChild(contentDiv);
|
||||
}
|
||||
|
||||
currentStepsContainer.appendChild(stepDiv);
|
||||
chatArea.scrollTop = chatArea.scrollHeight;
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const message = messageInput.value.trim();
|
||||
if (!message) return;
|
||||
|
||||
// 禁用输入
|
||||
messageInput.disabled = true;
|
||||
sendButton.disabled = true;
|
||||
sendButton.innerHTML = '<span class="loading"></span>';
|
||||
|
||||
// 显示用户消息
|
||||
addMessage(message, true);
|
||||
messageInput.value = '';
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/chat/stream-with-tools?conversationId=${conversationId}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ message: 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]);
|
||||
|
||||
if (eventType === 'user_message') {
|
||||
// 用户消息已经显示,跳过
|
||||
} else if (eventType === 'tool_call') {
|
||||
addStep('tool-call', data);
|
||||
} else if (eventType === 'tool_response') {
|
||||
addStep('tool-response', data);
|
||||
} else if (eventType === 'assistant_message') {
|
||||
addStep('assistant-message', data);
|
||||
} else if (eventType === 'final_response') {
|
||||
// 最终响应已经通过步骤显示,这里可以添加总结
|
||||
} else if (eventType === 'error') {
|
||||
addStep('error', data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
addMessage('发送失败: ' + error.message, false);
|
||||
} finally {
|
||||
// 恢复输入
|
||||
messageInput.disabled = false;
|
||||
sendButton.disabled = false;
|
||||
sendButton.textContent = '发送';
|
||||
messageInput.focus();
|
||||
currentStepsContainer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 回车发送
|
||||
messageInput.addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
});
|
||||
|
||||
// 页面加载完成后聚焦输入框
|
||||
window.addEventListener('load', () => {
|
||||
messageInput.focus();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user