feat: 将控制台应用改造为 Web 聊天界面
- 添加 ChatController 提供 REST API(流式/非流式聊天) - 添加 ChatService 封装 ChatClient 调用逻辑 - 添加前端聊天界面(index.html、style.css、chat.js) - 支持 SSE 流式响应和多轮对话记忆 - 集成 Markdown 渲染和代码高亮 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6b4a347688
commit
13181ef406
6 files changed
+1306
No files matched your search
@@ -0,0 +1,59 @@
|
|||||||
|
package org.springaicommunity.skills.controller;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.springaicommunity.skills.model.ChatRequest;
|
||||||
|
import org.springaicommunity.skills.service.ChatService;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/chat")
|
||||||
|
public class ChatController {
|
||||||
|
|
||||||
|
private final ChatService chatService;
|
||||||
|
|
||||||
|
public ChatController(ChatService chatService) {
|
||||||
|
this.chatService = chatService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 流式聊天接口(SSE)
|
||||||
|
*/
|
||||||
|
@PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||||
|
public Flux<String> chatStream(
|
||||||
|
@RequestParam(required = false) String conversationId,
|
||||||
|
@RequestBody ChatRequest request) {
|
||||||
|
String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString();
|
||||||
|
return chatService.chatStream(finalConversationId, request.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 非流式聊天接口(用于测试)
|
||||||
|
*/
|
||||||
|
@PostMapping("/chat")
|
||||||
|
public ResponseEntity<String> chat(
|
||||||
|
@RequestParam(required = false) String conversationId,
|
||||||
|
@RequestBody ChatRequest request) {
|
||||||
|
String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString();
|
||||||
|
String response = chatService.chat(finalConversationId, request.getMessage());
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空对话历史
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/clear")
|
||||||
|
public ResponseEntity<String> clear(@RequestParam String conversationId) {
|
||||||
|
chatService.clear(conversationId);
|
||||||
|
return ResponseEntity.ok("Conversation cleared: " + conversationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package org.springaicommunity.skills.model;
|
||||||
|
|
||||||
|
public class ChatRequest {
|
||||||
|
private String message;
|
||||||
|
|
||||||
|
public ChatRequest() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public ChatRequest(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMessage(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package org.springaicommunity.skills.service;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.ai.chat.client.ChatClient;
|
||||||
|
import org.springframework.ai.chat.memory.ChatMemory;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class ChatService {
|
||||||
|
|
||||||
|
private final ChatClient streamChatClient; // 流式用(不支持工具)
|
||||||
|
private final ChatClient chatClient; // 非流式用(支持工具)
|
||||||
|
private final ChatMemory chatMemory;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public ChatService(
|
||||||
|
@Qualifier("streamChatClient") ChatClient streamChatClient,
|
||||||
|
@Qualifier("chatClient") ChatClient chatClient,
|
||||||
|
ChatMemory chatMemory) {
|
||||||
|
this.streamChatClient = streamChatClient;
|
||||||
|
this.chatClient = chatClient;
|
||||||
|
this.chatMemory = chatMemory;
|
||||||
|
this.objectMapper = new ObjectMapper();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 流式聊天,返回 SSE 格式的响应(不支持工具调用)
|
||||||
|
*/
|
||||||
|
public Flux<String> chatStream(String conversationId, String userMessage) {
|
||||||
|
return streamChatClient.prompt()
|
||||||
|
.user(userMessage)
|
||||||
|
.advisors(a -> a.param("conversation_id", conversationId))
|
||||||
|
.stream()
|
||||||
|
.content()
|
||||||
|
.map(this::mapToSSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 非流式聊天(支持工具调用)
|
||||||
|
*/
|
||||||
|
public String chat(String conversationId, String userMessage) {
|
||||||
|
// 清空之前的工具调用记录
|
||||||
|
org.springaicommunity.skills.ToolCallCaptureAdvisor.clearToolCalls();
|
||||||
|
|
||||||
|
System.out.println("DEBUG: 开始聊天,conversationId=" + conversationId);
|
||||||
|
|
||||||
|
String content = chatClient.prompt()
|
||||||
|
.user(userMessage)
|
||||||
|
.advisors(a -> a.param("conversation_id", conversationId))
|
||||||
|
.call()
|
||||||
|
.content();
|
||||||
|
|
||||||
|
System.out.println("DEBUG: AI 回复内容: " + content);
|
||||||
|
|
||||||
|
// 获取工具调用信息
|
||||||
|
var toolCalls = org.springaicommunity.skills.ToolCallCaptureAdvisor.getToolCalls();
|
||||||
|
System.out.println("DEBUG: 捕获到的工具调用数量: " + (toolCalls != null ? toolCalls.size() : "null"));
|
||||||
|
|
||||||
|
// 如果有工具调用,将其附加到响应中
|
||||||
|
if (toolCalls != null && !toolCalls.isEmpty()) {
|
||||||
|
// 将工具调用信息作为 JSON 字符串附加到内容中
|
||||||
|
try {
|
||||||
|
String toolCallsJson = objectMapper.writeValueAsString(toolCalls);
|
||||||
|
System.out.println("DEBUG: 工具调用 JSON: " + toolCallsJson);
|
||||||
|
return content + "\n\n__TOOL_CALLS__:" + toolCallsJson;
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("ERROR: 序列化工具调用失败: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空对话历史
|
||||||
|
*/
|
||||||
|
public void clear(String conversationId) {
|
||||||
|
chatMemory.clear(conversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将文本内容映射为 SSE 事件
|
||||||
|
*/
|
||||||
|
private String mapToSSE(String content) {
|
||||||
|
try {
|
||||||
|
if (content != null && !content.isEmpty()) {
|
||||||
|
return formatSSE("text", objectMapper.writeValueAsString(
|
||||||
|
Map.of("content", content)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return formatSSE("error", "{\"message\": \"" + e.getMessage() + "\"}");
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化 SSE 事件
|
||||||
|
*/
|
||||||
|
private String formatSSE(String eventType, String data) {
|
||||||
|
return "event: " + eventType + "\ndata: " + data + "\n\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 900px;
|
||||||
|
height: 100vh;
|
||||||
|
background: #ffffff;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 头部样式 */
|
||||||
|
.header {
|
||||||
|
padding: 20px 30px;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-controls {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-indicator {
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 20px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-indicator.connected {
|
||||||
|
background: #10b981;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-indicator.disconnected {
|
||||||
|
background: #ef4444;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 消息区域 */
|
||||||
|
.messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 30px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 20px;
|
||||||
|
background: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
animation: slideIn 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes slideIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(10px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.user {
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
max-width: 70%;
|
||||||
|
padding: 12px 18px;
|
||||||
|
border-radius: 12px;
|
||||||
|
line-height: 1.6;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.user .message-content {
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content {
|
||||||
|
background: white;
|
||||||
|
color: #1f2937;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Markdown 样式 */
|
||||||
|
.message.assistant .message-content h1,
|
||||||
|
.message.assistant .message-content h2,
|
||||||
|
.message.assistant .message-content h3,
|
||||||
|
.message.assistant .message-content h4,
|
||||||
|
.message.assistant .message-content h5,
|
||||||
|
.message.assistant .message-content h6 {
|
||||||
|
margin-top: 16px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #111827;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
border-bottom: 2px solid #e5e7eb;
|
||||||
|
padding-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content h2 {
|
||||||
|
font-size: 20px;
|
||||||
|
border-bottom: 1px solid #e5e7eb;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content h3 {
|
||||||
|
font-size: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content p {
|
||||||
|
margin: 8px 0;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content ul,
|
||||||
|
.message.assistant .message-content ol {
|
||||||
|
margin: 8px 0;
|
||||||
|
padding-left: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content li {
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content ul {
|
||||||
|
list-style-type: disc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content ol {
|
||||||
|
list-style-type: decimal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content code {
|
||||||
|
background: #f3f4f6;
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 14px;
|
||||||
|
color: #dc2626;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content pre {
|
||||||
|
background: #1e293b;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
margin: 12px 0;
|
||||||
|
overflow-x: auto;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content pre .copy-button {
|
||||||
|
position: absolute;
|
||||||
|
top: 8px;
|
||||||
|
right: 8px;
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content pre .copy-button:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content pre .copy-button.copied {
|
||||||
|
background: #10b981;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content pre code {
|
||||||
|
background: transparent;
|
||||||
|
padding: 0;
|
||||||
|
color: #e2e8f0;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content blockquote {
|
||||||
|
border-left: 4px solid #667eea;
|
||||||
|
padding-left: 16px;
|
||||||
|
margin: 12px 0;
|
||||||
|
color: #6b7280;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content a {
|
||||||
|
color: #667eea;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content th,
|
||||||
|
.message.assistant .message-content td {
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
padding: 8px 12px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content th {
|
||||||
|
background: #f9fafb;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content tr:hover {
|
||||||
|
background: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content img {
|
||||||
|
max-width: 100%;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message.assistant .message-content hr {
|
||||||
|
border: none;
|
||||||
|
border-top: 2px solid #e5e7eb;
|
||||||
|
margin: 16px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 工具调用样式 */
|
||||||
|
.tool-call {
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 16px;
|
||||||
|
margin: 12px 0;
|
||||||
|
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
|
||||||
|
animation: slideIn 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-call-header {
|
||||||
|
font-weight: 600;
|
||||||
|
color: white;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-call-details {
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
background: rgba(255, 255, 255, 0.95);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
color: #1f2937;
|
||||||
|
max-height: 200px;
|
||||||
|
overflow-y: auto;
|
||||||
|
border: 1px solid rgba(102, 126, 234, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-result {
|
||||||
|
background: linear-gradient(135deg, #10b981 0%, #059669 100%);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 16px;
|
||||||
|
margin: 12px 0;
|
||||||
|
box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
|
||||||
|
animation: slideIn 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-result-header {
|
||||||
|
font-weight: 600;
|
||||||
|
color: white;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-result-content {
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
background: rgba(255, 255, 255, 0.95);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
max-height: 300px;
|
||||||
|
overflow-y: auto;
|
||||||
|
color: #1f2937;
|
||||||
|
border: 1px solid rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 打字动画 */
|
||||||
|
.typing-indicator {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 12px 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator span {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
background: #9ca3af;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: typing 1.4s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator span:nth-child(2) {
|
||||||
|
animation-delay: 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-indicator span:nth-child(3) {
|
||||||
|
animation-delay: 0.4s;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes typing {
|
||||||
|
0%, 60%, 100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
30% {
|
||||||
|
transform: translateY(-10px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 输入区域 */
|
||||||
|
.input-container {
|
||||||
|
padding: 20px 30px;
|
||||||
|
background: white;
|
||||||
|
border-top: 1px solid #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-form {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border: 2px solid #e5e7eb;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
font-family: inherit;
|
||||||
|
resize: none;
|
||||||
|
min-height: 50px;
|
||||||
|
max-height: 150px;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #667eea;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-send {
|
||||||
|
padding: 12px 24px;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.1s, box-shadow 0.2s;
|
||||||
|
min-width: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-send:hover:not(:disabled) {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-send:active:not(:disabled) {
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-send:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
padding: 8px 16px;
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
color: white;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 切换按钮样式 */
|
||||||
|
.toggle-container {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 6px 12px;
|
||||||
|
background: rgba(255, 255, 255, 0.2);
|
||||||
|
border-radius: 20px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-container:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-container input[type="checkbox"] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-label {
|
||||||
|
color: white;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-switch {
|
||||||
|
position: relative;
|
||||||
|
width: 44px;
|
||||||
|
height: 24px;
|
||||||
|
background: rgba(255, 255, 255, 0.3);
|
||||||
|
border-radius: 12px;
|
||||||
|
transition: background 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-switch::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
left: 2px;
|
||||||
|
top: 2px;
|
||||||
|
background: white;
|
||||||
|
border-radius: 50%;
|
||||||
|
transition: transform 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-container input[type="checkbox"]:checked + .toggle-label + .toggle-switch {
|
||||||
|
background: #10b981;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-container input[type="checkbox"]:checked + .toggle-label + .toggle-switch::before {
|
||||||
|
transform: translateX(20px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 错误消息 */
|
||||||
|
.error-message {
|
||||||
|
background: #fef2f2;
|
||||||
|
border-left: 3px solid #ef4444;
|
||||||
|
padding: 12px;
|
||||||
|
margin: 10px 0;
|
||||||
|
border-radius: 6px;
|
||||||
|
color: #991b1b;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 滚动条样式 */
|
||||||
|
.messages::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages::-webkit-scrollbar-track {
|
||||||
|
background: #f1f1f1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages::-webkit-scrollbar-thumb {
|
||||||
|
background: #cbd5e1;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #94a3b8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 响应式设计 */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.header {
|
||||||
|
padding: 15px 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.messages {
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
max-width: 85%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-container {
|
||||||
|
padding: 15px 20px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<!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 Chat</title>
|
||||||
|
<link rel="stylesheet" href="css/style.css">
|
||||||
|
|
||||||
|
<!-- Marked.js - Markdown 解析器 -->
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||||
|
|
||||||
|
<!-- Highlight.js - 代码高亮 -->
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css">
|
||||||
|
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
|
||||||
|
|
||||||
|
<!-- DOMPurify - HTML 清理(防止 XSS) -->
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<!-- 头部 -->
|
||||||
|
<header class="header">
|
||||||
|
<h1>🤖 Spring AI Skills Chat</h1>
|
||||||
|
<div class="header-controls">
|
||||||
|
<span id="connection-status" class="status-indicator disconnected">未连接</span>
|
||||||
|
<label class="toggle-container">
|
||||||
|
<input type="checkbox" id="tool-toggle" checked>
|
||||||
|
<span class="toggle-label">启用工具调用</span>
|
||||||
|
<span class="toggle-switch"></span>
|
||||||
|
</label>
|
||||||
|
<button id="clear-btn" class="btn-secondary">清空对话</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- 消息区域 -->
|
||||||
|
<div id="messages" class="messages"></div>
|
||||||
|
|
||||||
|
<!-- 输入区域 -->
|
||||||
|
<div class="input-container">
|
||||||
|
<form id="chat-form" class="chat-form">
|
||||||
|
<textarea
|
||||||
|
id="user-input"
|
||||||
|
class="chat-input"
|
||||||
|
placeholder="输入消息... (Shift+Enter 换行, Enter 发送)"
|
||||||
|
rows="1"
|
||||||
|
required></textarea>
|
||||||
|
<button type="submit" class="btn-send" id="send-btn" disabled>发送</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="js/chat.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
// 获取 DOM 元素
|
||||||
|
const messagesContainer = document.getElementById('messages');
|
||||||
|
const chatForm = document.getElementById('chat-form');
|
||||||
|
const userInput = document.getElementById('user-input');
|
||||||
|
const sendBtn = document.getElementById('send-btn');
|
||||||
|
const clearBtn = document.getElementById('clear-btn');
|
||||||
|
const connectionStatus = document.getElementById('connection-status');
|
||||||
|
const toolToggle = document.getElementById('tool-toggle');
|
||||||
|
|
||||||
|
// 会话 ID 管理
|
||||||
|
let conversationId = localStorage.getItem('conversationId');
|
||||||
|
|
||||||
|
if (!conversationId) {
|
||||||
|
conversationId = generateConversationId();
|
||||||
|
localStorage.setItem('conversationId', conversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成新的会话 ID
|
||||||
|
function generateConversationId() {
|
||||||
|
return 'conv-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动调整文本框高度
|
||||||
|
userInput.addEventListener('input', function() {
|
||||||
|
this.style.height = 'auto';
|
||||||
|
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
|
||||||
|
|
||||||
|
// 启用/禁用发送按钮
|
||||||
|
sendBtn.disabled = this.value.trim() === '';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 处理 Shift+Enter 换行,Enter 发送
|
||||||
|
userInput.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (this.value.trim() !== '') {
|
||||||
|
chatForm.dispatchEvent(new Event('submit'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 表单提交
|
||||||
|
chatForm.addEventListener('submit', async function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const message = userInput.value.trim();
|
||||||
|
if (!message) return;
|
||||||
|
|
||||||
|
// 清空输入框
|
||||||
|
userInput.value = '';
|
||||||
|
userInput.style.height = 'auto';
|
||||||
|
sendBtn.disabled = true;
|
||||||
|
|
||||||
|
// 添加用户消息到界面
|
||||||
|
appendMessage('user', message);
|
||||||
|
|
||||||
|
// 根据切换状态选择接口
|
||||||
|
const useTools = toolToggle.checked;
|
||||||
|
if (useTools) {
|
||||||
|
// 使用工具调用(非流式)
|
||||||
|
await sendMessageWithTools(message);
|
||||||
|
} else {
|
||||||
|
// 使用流式响应
|
||||||
|
await streamMessage(message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 清空对话
|
||||||
|
clearBtn.addEventListener('click', async function() {
|
||||||
|
if (!confirm('确定要清空对话吗?')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/chat/clear?conversationId=${conversationId}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
// 生成新的会话 ID
|
||||||
|
conversationId = generateConversationId();
|
||||||
|
localStorage.setItem('conversationId', conversationId);
|
||||||
|
|
||||||
|
// 清空消息区域
|
||||||
|
messagesContainer.innerHTML = '';
|
||||||
|
appendMessage('assistant', '对话已清空,我们可以重新开始!');
|
||||||
|
} else {
|
||||||
|
showError('清空对话失败');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('清空对话错误:', error);
|
||||||
|
showError('清空对话时发生错误');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 流式发送消息
|
||||||
|
async function streamMessage(message) {
|
||||||
|
updateConnectionStatus(true);
|
||||||
|
|
||||||
|
// 创建助手消息元素
|
||||||
|
const assistantMessageElement = createAssistantMessage();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/chat/stream?conversationId=${conversationId}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ message })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let currentContent = '';
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
|
||||||
|
if (done) break;
|
||||||
|
|
||||||
|
const chunk = decoder.decode(value);
|
||||||
|
const events = parseSSE(chunk);
|
||||||
|
|
||||||
|
for (const event of events) {
|
||||||
|
if (event.type === 'text') {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
const content = data.content;
|
||||||
|
currentContent += content;
|
||||||
|
updateAssistantMessage(assistantMessageElement, currentContent);
|
||||||
|
} else if (event.type === 'error') {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
showError(data.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 滚动到底部
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('流式响应错误:', error);
|
||||||
|
showError('连接错误: ' + error.message);
|
||||||
|
assistantMessageElement.remove();
|
||||||
|
} finally {
|
||||||
|
updateConnectionStatus(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 非流式发送消息(支持工具调用)
|
||||||
|
async function sendMessageWithTools(message) {
|
||||||
|
updateConnectionStatus(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/chat/chat?conversationId=${conversationId}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ message })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = await response.text();
|
||||||
|
|
||||||
|
// 提取工具调用信息
|
||||||
|
let toolCalls = null;
|
||||||
|
if (content.includes('__TOOL_CALLS__:')) {
|
||||||
|
const parts = content.split('__TOOL_CALLS__:');
|
||||||
|
content = parts[0].trim(); // 移除末尾的空白
|
||||||
|
try {
|
||||||
|
toolCalls = JSON.parse(parts[1]);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('解析工具调用信息失败:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先显示工具调用(如果有)
|
||||||
|
if (toolCalls && toolCalls.length > 0) {
|
||||||
|
toolCalls.forEach(toolCall => {
|
||||||
|
if (toolCall.type === 'tool_call') {
|
||||||
|
appendToolCall(toolCall.name, toolCall.arguments);
|
||||||
|
} else if (toolCall.type === 'tool_result' && toolCall.result) {
|
||||||
|
appendToolResult(toolCall.name, toolCall.result);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 然后显示 AI 回复
|
||||||
|
const assistantMessageElement = createAssistantMessageWithoutLoading();
|
||||||
|
updateAssistantMessage(assistantMessageElement, content);
|
||||||
|
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('工具调用错误:', error);
|
||||||
|
showError('连接错误: ' + error.message);
|
||||||
|
} finally {
|
||||||
|
updateConnectionStatus(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建助手消息元素(不显示加载动画)
|
||||||
|
function createAssistantMessageWithoutLoading() {
|
||||||
|
const messageDiv = document.createElement('div');
|
||||||
|
messageDiv.className = 'message assistant';
|
||||||
|
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'message-content';
|
||||||
|
|
||||||
|
messageDiv.appendChild(contentDiv);
|
||||||
|
messagesContainer.appendChild(messageDiv);
|
||||||
|
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
|
return messageDiv;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示工具调用(已废弃,直接在 sendMessageWithTools 中处理)
|
||||||
|
|
||||||
|
// 添加工具调用展示
|
||||||
|
function appendToolCall(name, arguments) {
|
||||||
|
const toolCallDiv = document.createElement('div');
|
||||||
|
toolCallDiv.className = 'tool-call';
|
||||||
|
|
||||||
|
const headerDiv = document.createElement('div');
|
||||||
|
headerDiv.className = 'tool-call-header';
|
||||||
|
headerDiv.innerHTML = '⚙️ 调用工具: ' + name;
|
||||||
|
|
||||||
|
const detailsDiv = document.createElement('div');
|
||||||
|
detailsDiv.className = 'tool-call-details';
|
||||||
|
|
||||||
|
// 格式化参数显示
|
||||||
|
let argsText = '';
|
||||||
|
if (typeof arguments === 'string') {
|
||||||
|
argsText = arguments;
|
||||||
|
} else {
|
||||||
|
argsText = JSON.stringify(arguments, null, 2);
|
||||||
|
}
|
||||||
|
detailsDiv.textContent = '参数: ' + argsText;
|
||||||
|
|
||||||
|
toolCallDiv.appendChild(headerDiv);
|
||||||
|
toolCallDiv.appendChild(detailsDiv);
|
||||||
|
|
||||||
|
messagesContainer.appendChild(toolCallDiv);
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加工具结果展示
|
||||||
|
function appendToolResult(name, result) {
|
||||||
|
const toolResultDiv = document.createElement('div');
|
||||||
|
toolResultDiv.className = 'tool-result';
|
||||||
|
|
||||||
|
const headerDiv = document.createElement('div');
|
||||||
|
headerDiv.className = 'tool-result-header';
|
||||||
|
headerDiv.innerHTML = '📄 工具返回: ' + name;
|
||||||
|
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'tool-result-content';
|
||||||
|
|
||||||
|
// 格式化结果显示
|
||||||
|
let resultText = '';
|
||||||
|
if (typeof result === 'string') {
|
||||||
|
resultText = result;
|
||||||
|
} else {
|
||||||
|
resultText = JSON.stringify(result, null, 2);
|
||||||
|
}
|
||||||
|
contentDiv.textContent = resultText;
|
||||||
|
|
||||||
|
toolResultDiv.appendChild(headerDiv);
|
||||||
|
toolResultDiv.appendChild(contentDiv);
|
||||||
|
|
||||||
|
messagesContainer.appendChild(toolResultDiv);
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析 SSE 事件
|
||||||
|
function parseSSE(chunk) {
|
||||||
|
const events = [];
|
||||||
|
const lines = chunk.split('\n');
|
||||||
|
|
||||||
|
let currentEvent = { type: '', data: '' };
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (line.startsWith('event: ')) {
|
||||||
|
currentEvent.type = line.substring(7);
|
||||||
|
} else if (line.startsWith('data: ')) {
|
||||||
|
currentEvent.data = line.substring(6);
|
||||||
|
|
||||||
|
if (currentEvent.type && currentEvent.data) {
|
||||||
|
events.push({ ...currentEvent });
|
||||||
|
currentEvent = { type: '', data: '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加消息到界面
|
||||||
|
function appendMessage(role, content) {
|
||||||
|
const messageDiv = document.createElement('div');
|
||||||
|
messageDiv.className = `message ${role}`;
|
||||||
|
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'message-content';
|
||||||
|
|
||||||
|
if (role === 'assistant') {
|
||||||
|
// 渲染 Markdown
|
||||||
|
const htmlContent = marked.parse(content);
|
||||||
|
const cleanHtml = DOMPurify.sanitize(htmlContent);
|
||||||
|
contentDiv.innerHTML = cleanHtml;
|
||||||
|
|
||||||
|
// 高亮代码块并添加复制按钮
|
||||||
|
setTimeout(() => {
|
||||||
|
contentDiv.querySelectorAll('pre code').forEach((block) => {
|
||||||
|
hljs.highlightElement(block);
|
||||||
|
|
||||||
|
// 添加复制按钮
|
||||||
|
const pre = block.parentElement;
|
||||||
|
const copyBtn = document.createElement('button');
|
||||||
|
copyBtn.className = 'copy-button';
|
||||||
|
copyBtn.textContent = '复制';
|
||||||
|
|
||||||
|
copyBtn.addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(block.textContent);
|
||||||
|
copyBtn.textContent = '已复制!';
|
||||||
|
copyBtn.classList.add('copied');
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
copyBtn.textContent = '复制';
|
||||||
|
copyBtn.classList.remove('copied');
|
||||||
|
}, 2000);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('复制失败:', err);
|
||||||
|
copyBtn.textContent = '复制失败';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
pre.style.position = 'relative';
|
||||||
|
pre.appendChild(copyBtn);
|
||||||
|
});
|
||||||
|
}, 0);
|
||||||
|
} else {
|
||||||
|
// 用户消息不渲染 Markdown
|
||||||
|
contentDiv.textContent = content;
|
||||||
|
}
|
||||||
|
|
||||||
|
messageDiv.appendChild(contentDiv);
|
||||||
|
messagesContainer.appendChild(messageDiv);
|
||||||
|
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建助手消息元素
|
||||||
|
function createAssistantMessage() {
|
||||||
|
const messageDiv = document.createElement('div');
|
||||||
|
messageDiv.className = 'message assistant';
|
||||||
|
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'message-content';
|
||||||
|
contentDiv.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
|
||||||
|
|
||||||
|
messageDiv.appendChild(contentDiv);
|
||||||
|
messagesContainer.appendChild(messageDiv);
|
||||||
|
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
|
return messageDiv;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新助手消息内容
|
||||||
|
function updateAssistantMessage(messageElement, content) {
|
||||||
|
const contentDiv = messageElement.querySelector('.message-content');
|
||||||
|
|
||||||
|
// 渲染 Markdown
|
||||||
|
const htmlContent = marked.parse(content);
|
||||||
|
|
||||||
|
// 清理 HTML(防止 XSS 攻击)
|
||||||
|
const cleanHtml = DOMPurify.sanitize(htmlContent);
|
||||||
|
|
||||||
|
contentDiv.innerHTML = cleanHtml;
|
||||||
|
|
||||||
|
// 高亮代码块并添加复制按钮
|
||||||
|
contentDiv.querySelectorAll('pre code').forEach((block) => {
|
||||||
|
hljs.highlightElement(block);
|
||||||
|
|
||||||
|
// 添加复制按钮
|
||||||
|
const pre = block.parentElement;
|
||||||
|
const copyBtn = document.createElement('button');
|
||||||
|
copyBtn.className = 'copy-button';
|
||||||
|
copyBtn.textContent = '复制';
|
||||||
|
|
||||||
|
copyBtn.addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(block.textContent);
|
||||||
|
copyBtn.textContent = '已复制!';
|
||||||
|
copyBtn.classList.add('copied');
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
copyBtn.textContent = '复制';
|
||||||
|
copyBtn.classList.remove('copied');
|
||||||
|
}, 2000);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('复制失败:', err);
|
||||||
|
copyBtn.textContent = '复制失败';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
pre.style.position = 'relative';
|
||||||
|
pre.appendChild(copyBtn);
|
||||||
|
});
|
||||||
|
|
||||||
|
scrollToBottom();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示错误消息
|
||||||
|
function showError(message) {
|
||||||
|
const errorDiv = document.createElement('div');
|
||||||
|
errorDiv.className = 'error-message';
|
||||||
|
errorDiv.textContent = '❌ 错误: ' + message;
|
||||||
|
|
||||||
|
messagesContainer.appendChild(errorDiv);
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
|
// 3秒后自动移除
|
||||||
|
setTimeout(() => {
|
||||||
|
errorDiv.remove();
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新连接状态
|
||||||
|
function updateConnectionStatus(connected) {
|
||||||
|
if (connected) {
|
||||||
|
connectionStatus.textContent = '已连接';
|
||||||
|
connectionStatus.className = 'status-indicator connected';
|
||||||
|
} else {
|
||||||
|
connectionStatus.textContent = '未连接';
|
||||||
|
connectionStatus.className = 'status-indicator disconnected';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 滚动到底部
|
||||||
|
function scrollToBottom() {
|
||||||
|
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载时聚焦输入框
|
||||||
|
window.addEventListener('load', () => {
|
||||||
|
userInput.focus();
|
||||||
|
|
||||||
|
// 配置 marked.js
|
||||||
|
marked.setOptions({
|
||||||
|
breaks: true, // 支持 GFM 换行
|
||||||
|
gfm: true, // 启用 GitHub Flavored Markdown
|
||||||
|
highlight: function(code, lang) {
|
||||||
|
if (lang && hljs.getLanguage(lang)) {
|
||||||
|
try {
|
||||||
|
return hljs.highlight(code, { language: lang }).value;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('代码高亮错误:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hljs.highlightAuto(code).value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 添加欢迎消息
|
||||||
|
const welcomeMessage = `## 👋 欢迎使用 Spring AI Skills Chat
|
||||||
|
|
||||||
|
我可以帮助你完成各种任务,包括:
|
||||||
|
|
||||||
|
- 💬 **普通对话**(关闭"启用工具调用"使用流式响应)
|
||||||
|
- 🔧 **执行 Shell 命令**
|
||||||
|
- 📁 **读写文件**
|
||||||
|
- 🎯 **使用自定义 Skills**
|
||||||
|
|
||||||
|
### 快速开始:
|
||||||
|
|
||||||
|
1. **开启工具调用**:点击右上角的"启用工具调用"开关
|
||||||
|
2. **发送指令**:例如"列出当前目录的文件"
|
||||||
|
3. **查看执行过程**:工具调用和结果会实时显示
|
||||||
|
|
||||||
|
现在就开始吧!🚀`;
|
||||||
|
|
||||||
|
const assistantDiv = document.createElement('div');
|
||||||
|
assistantDiv.className = 'message assistant';
|
||||||
|
const contentDiv = document.createElement('div');
|
||||||
|
contentDiv.className = 'message-content';
|
||||||
|
|
||||||
|
const htmlContent = marked.parse(welcomeMessage);
|
||||||
|
const cleanHtml = DOMPurify.sanitize(htmlContent);
|
||||||
|
contentDiv.innerHTML = cleanHtml;
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
contentDiv.querySelectorAll('pre code').forEach((block) => {
|
||||||
|
hljs.highlightElement(block);
|
||||||
|
});
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
assistantDiv.appendChild(contentDiv);
|
||||||
|
messagesContainer.appendChild(assistantDiv);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 页面卸载时保存会话 ID
|
||||||
|
window.addEventListener('beforeunload', () => {
|
||||||
|
localStorage.setItem('conversationId', conversationId);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user