feat: 实现会话管理和 AI 回复保存功能

## 新增功能
- 实现会话持久化存储(JSON 文件)
- 支持会话列表显示、切换、创建、删除
- 自动保存用户消息和 AI 回复
- 优化 Markdown 渲染样式(标题、列表、代码块、表格等)
- 添加过程数据可视化(思考步骤、工具调用、响应)

## 技术改进
- 新增 ConversationMessage、ConversationMetadata 模型
- 新增 ConversationStorageService 服务(JSON 文件存储)
- 在 ChatService 中添加流式响应完成后保存 AI 回复的逻辑
- 优化删除会话逻辑:删除当前会话后切换到现有会话,而非自动创建新会话
- 优化应用初始化:优先使用现有会话,仅在没有会话时才创建新会话

## 依赖更新
- 添加 jackson-datatype-jsr310 支持 Java 8 DateTime

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-31 22:03:28 +08:00
1 parent 1ffd256c9d
commit fd09a55614
11 files changed
+2697 -993

No files matched your search

@@ -1,17 +1,15 @@
package org.springaicommunity.skills.controller;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springaicommunity.skills.model.ChatRequest;
import org.springaicommunity.skills.service.ChatService;
import org.springaicommunity.skills.service.ConversationStorageService;
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 org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
@@ -20,9 +18,11 @@ import reactor.core.publisher.Flux;
public class ChatController {
private final ChatService chatService;
private final ConversationStorageService storageService;
public ChatController(ChatService chatService) {
public ChatController(ChatService chatService, ConversationStorageService storageService) {
this.chatService = chatService;
this.storageService = storageService;
}
/**
@@ -33,6 +33,11 @@ public class ChatController {
@RequestParam(required = false) String conversationId,
@RequestBody ChatRequest request) {
String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString();
// 保存用户消息
storageService.saveMessage(finalConversationId,
new org.springaicommunity.skills.model.ConversationMessage("user", request.getMessage()));
return chatService.chatStream(finalConversationId, request.getMessage());
}
@@ -44,7 +49,21 @@ public class ChatController {
@RequestParam(required = false) String conversationId,
@RequestBody ChatRequest request) {
String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString();
return chatService.chatStreamWithTools(finalConversationId, request.getMessage());
// 保存用户消息
storageService.saveMessage(finalConversationId,
new org.springaicommunity.skills.model.ConversationMessage("user", request.getMessage()));
return chatService.chatStreamWithTools(finalConversationId, request.getMessage())
.doOnComplete(() -> {
// 流完成后,从内存中加载会话历史并保存
// 注意:这里需要从 ChatMemory 或其他地方获取完整的对话
// 暂时简化处理
logger.info("会话流完成: {}", finalConversationId);
})
.doOnError(error -> {
logger.error("会话流错误: {}", error.getMessage());
});
}
/**
@@ -55,7 +74,17 @@ public class ChatController {
@RequestParam(required = false) String conversationId,
@RequestBody ChatRequest request) {
String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString();
// 保存用户消息
storageService.saveMessage(finalConversationId,
new org.springaicommunity.skills.model.ConversationMessage("user", request.getMessage()));
String response = chatService.chat(finalConversationId, request.getMessage());
// 保存 AI 响应
storageService.saveMessage(finalConversationId,
new org.springaicommunity.skills.model.ConversationMessage("assistant", response));
return ResponseEntity.ok(response);
}
@@ -65,6 +94,79 @@ public class ChatController {
@DeleteMapping("/clear")
public ResponseEntity<String> clear(@RequestParam String conversationId) {
chatService.clear(conversationId);
storageService.deleteConversation(conversationId);
return ResponseEntity.ok("Conversation cleared: " + conversationId);
}
// ==================== 会话管理 API ====================
/**
* 获取所有会话列表
*/
@GetMapping("/conversations")
public ResponseEntity<List<org.springaicommunity.skills.model.ConversationMetadata>> listConversations() {
return ResponseEntity.ok(storageService.listConversations());
}
/**
* 创建新会话
*/
@PostMapping("/conversations")
public ResponseEntity<org.springaicommunity.skills.model.ConversationMetadata> createConversation(
@RequestBody Map<String, String> request) {
String title = request.getOrDefault("title", "新对话");
org.springaicommunity.skills.model.ConversationMetadata metadata = storageService.createConversation(title);
return ResponseEntity.ok(metadata);
}
/**
* 获取会话消息
*/
@GetMapping("/conversations/{conversationId}/messages")
public ResponseEntity<List<org.springaicommunity.skills.model.ConversationMessage>> getMessages(
@PathVariable String conversationId) {
return ResponseEntity.ok(storageService.loadMessages(conversationId));
}
/**
* 获取会话元数据
*/
@GetMapping("/conversations/{conversationId}")
public ResponseEntity<org.springaicommunity.skills.model.ConversationMetadata> getConversation(
@PathVariable String conversationId) {
org.springaicommunity.skills.model.ConversationMetadata metadata = storageService.getMetadata(conversationId);
if (metadata == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(metadata);
}
/**
* 更新会话标题
*/
@PutMapping("/conversations/{conversationId}")
public ResponseEntity<Void> updateConversation(
@PathVariable String conversationId,
@RequestBody Map<String, String> request) {
String title = request.get("title");
if (title != null) {
storageService.updateTitle(conversationId, title);
}
return ResponseEntity.ok().build();
}
/**
* 删除会话
*/
@DeleteMapping("/conversations/{conversationId}")
public ResponseEntity<Void> deleteConversation(@PathVariable String conversationId) {
boolean deleted = storageService.deleteConversation(conversationId);
if (deleted) {
return ResponseEntity.ok().build();
}
return ResponseEntity.notFound().build();
}
private static final org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(ChatController.class);
}
@@ -0,0 +1,64 @@
package org.springaicommunity.skills.model;
import java.time.LocalDateTime;
/**
* 会话消息模型
*/
public class ConversationMessage {
private String role; // user 或 assistant
private String content; // 消息内容
private LocalDateTime timestamp; // 时间戳
private String type; // 消息类型:text, tool_call, tool_response
public ConversationMessage() {
}
public ConversationMessage(String role, String content) {
this.role = role;
this.content = content;
this.timestamp = LocalDateTime.now();
this.type = "text";
}
public ConversationMessage(String role, String content, String type) {
this.role = role;
this.content = content;
this.timestamp = LocalDateTime.now();
this.type = type;
}
// Getters and Setters
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
@@ -0,0 +1,67 @@
package org.springaicommunity.skills.model;
import java.time.LocalDateTime;
/**
* 会话元数据
*/
public class ConversationMetadata {
private String id; // 会话ID
private String title; // 会话标题
private LocalDateTime createdAt; // 创建时间
private LocalDateTime updatedAt; // 更新时间
private int messageCount; // 消息数量
public ConversationMetadata() {
}
public ConversationMetadata(String id, String title) {
this.id = id;
this.title = title;
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
this.messageCount = 0;
}
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public int getMessageCount() {
return messageCount;
}
public void setMessageCount(int messageCount) {
this.messageCount = messageCount;
}
}
@@ -21,16 +21,19 @@ public class ChatService {
private final ChatClient.Builder chatClientBuilder; // 用于创建带自定义 Advisor 的客户端
private final ChatMemory chatMemory;
private final ObjectMapper objectMapper;
private final ConversationStorageService storageService;
public ChatService(
@Qualifier("streamChatClient") ChatClient streamChatClient,
@Qualifier("chatClient") ChatClient chatClient,
@Qualifier("chatClientBuilder") ChatClient.Builder chatClientBuilder,
ChatMemory chatMemory) {
ChatMemory chatMemory,
ConversationStorageService storageService) {
this.streamChatClient = streamChatClient;
this.chatClient = chatClient;
this.chatClientBuilder = chatClientBuilder;
this.chatMemory = chatMemory;
this.storageService = storageService;
this.objectMapper = new ObjectMapper();
}
@@ -38,11 +41,27 @@ public class ChatService {
* 流式聊天,返回 SSE 格式的响应(不支持工具调用)
*/
public Flux<String> chatStream(String conversationId, String userMessage) {
// 收集完整内容用于保存
StringBuilder fullContent = new StringBuilder();
return streamChatClient.prompt()
.user(userMessage)
.advisors(a -> a.param("conversation_id", conversationId))
.stream()
.content()
.doOnNext(chunk -> {
// 收集内容片段
if (chunk != null) {
fullContent.append(chunk);
}
})
.doOnComplete(() -> {
// 流完成时保存完整响应
if (fullContent.length() > 0) {
storageService.saveMessage(conversationId,
new org.springaicommunity.skills.model.ConversationMessage("assistant", fullContent.toString()));
}
})
.map(this::mapToSSE);
}
@@ -81,6 +100,10 @@ public class ChatService {
);
sink.tryEmitNext(finalEvent);
// 保存 AI 响应
storageService.saveMessage(conversationId,
new org.springaicommunity.skills.model.ConversationMessage("assistant", content));
// 完成流
sink.tryEmitComplete();
@@ -0,0 +1,227 @@
package org.springaicommunity.skills.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springaicommunity.skills.model.ConversationMessage;
import org.springaicommunity.skills.model.ConversationMetadata;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 会话存储服务 - 使用 JSON 文件存储会话数据
*/
@Service
public class ConversationStorageService {
private static final Logger logger = LoggerFactory.getLogger(ConversationStorageService.class);
@Value("${conversation.storage.path:./conversations}")
private String storagePath;
private Path storageDirectory;
private final ObjectMapper objectMapper;
public ConversationStorageService() {
this.objectMapper = new ObjectMapper();
this.objectMapper.registerModule(new JavaTimeModule());
}
@PostConstruct
public void init() {
try {
storageDirectory = Paths.get(storagePath);
if (!Files.exists(storageDirectory)) {
Files.createDirectories(storageDirectory);
logger.info("创建会话存储目录: {}", storageDirectory.toAbsolutePath());
}
} catch (IOException e) {
logger.error("初始化会话存储目录失败: {}", e.getMessage(), e);
}
}
/**
* 保存会话消息
*/
public void saveMessage(String conversationId, ConversationMessage message) {
try {
Path messageFile = getMessageFilePath(conversationId);
List<ConversationMessage> messages = loadMessages(conversationId);
messages.add(message);
objectMapper.writerWithDefaultPrettyPrinter()
.writeValue(messageFile.toFile(), messages);
// 更新元数据
updateMetadata(conversationId, messages.size());
logger.debug("保存消息到会话 {}: {}", conversationId, message.getRole());
} catch (IOException e) {
logger.error("保存消息失败: {}", e.getMessage(), e);
}
}
/**
* 批量保存会话消息
*/
public void saveMessages(String conversationId, List<ConversationMessage> messages) {
try {
Path messageFile = getMessageFilePath(conversationId);
objectMapper.writerWithDefaultPrettyPrinter()
.writeValue(messageFile.toFile(), messages);
updateMetadata(conversationId, messages.size());
logger.info("保存 {} 条消息到会话 {}", messages.size(), conversationId);
} catch (IOException e) {
logger.error("批量保存消息失败: {}", e.getMessage(), e);
}
}
/**
* 加载会话消息
*/
public List<ConversationMessage> loadMessages(String conversationId) {
try {
Path messageFile = getMessageFilePath(conversationId);
if (!Files.exists(messageFile)) {
return new ArrayList<>();
}
ConversationMessage[] array = objectMapper.readValue(messageFile.toFile(), ConversationMessage[].class);
return new ArrayList<>(Arrays.asList(array));
} catch (IOException e) {
logger.error("加载消息失败: {}", e.getMessage(), e);
return new ArrayList<>();
}
}
/**
* 获取所有会话列表
*/
public List<ConversationMetadata> listConversations() {
try (Stream<Path> paths = Files.list(storageDirectory)) {
return paths
.filter(path -> path.toString().endsWith("-metadata.json"))
.map(this::loadMetadata)
.filter(Objects::nonNull)
.sorted((a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt()))
.collect(Collectors.toList());
} catch (IOException e) {
logger.error("列出会话失败: {}", e.getMessage(), e);
return new ArrayList<>();
}
}
/**
* 获取会话元数据
*/
public ConversationMetadata getMetadata(String conversationId) {
Path metadataFile = getMetadataFilePath(conversationId);
if (!Files.exists(metadataFile)) {
return null;
}
return loadMetadata(metadataFile);
}
/**
* 创建新会话
*/
public ConversationMetadata createConversation(String title) {
String id = UUID.randomUUID().toString();
ConversationMetadata metadata = new ConversationMetadata(id, title);
saveMetadata(metadata);
return metadata;
}
/**
* 删除会话
*/
public boolean deleteConversation(String conversationId) {
try {
Path messageFile = getMessageFilePath(conversationId);
Path metadataFile = getMetadataFilePath(conversationId);
boolean deleted = false;
if (Files.exists(messageFile)) {
Files.delete(messageFile);
deleted = true;
}
if (Files.exists(metadataFile)) {
Files.delete(metadataFile);
deleted = true;
}
logger.info("删除会话 {}: {}", conversationId, deleted);
return deleted;
} catch (IOException e) {
logger.error("删除会话失败: {}", e.getMessage(), e);
return false;
}
}
/**
* 更新会话标题
*/
public void updateTitle(String conversationId, String title) {
ConversationMetadata metadata = getMetadata(conversationId);
if (metadata != null) {
metadata.setTitle(title);
metadata.setUpdatedAt(LocalDateTime.now());
saveMetadata(metadata);
}
}
// ==================== 私有方法 ====================
private Path getMessageFilePath(String conversationId) {
return storageDirectory.resolve(conversationId + "-messages.json");
}
private Path getMetadataFilePath(String conversationId) {
return storageDirectory.resolve(conversationId + "-metadata.json");
}
private void saveMetadata(ConversationMetadata metadata) {
try {
Path metadataFile = getMetadataFilePath(metadata.getId());
objectMapper.writerWithDefaultPrettyPrinter()
.writeValue(metadataFile.toFile(), metadata);
} catch (IOException e) {
logger.error("保存元数据失败: {}", e.getMessage(), e);
}
}
private ConversationMetadata loadMetadata(Path metadataFile) {
try {
return objectMapper.readValue(metadataFile.toFile(), ConversationMetadata.class);
} catch (IOException e) {
logger.error("加载元数据失败: {}", e.getMessage(), e);
return null;
}
}
private void updateMetadata(String conversationId, int messageCount) {
ConversationMetadata metadata = getMetadata(conversationId);
if (metadata == null) {
// 如果没有元数据,创建一个默认的
metadata = new ConversationMetadata(conversationId, "新对话 " + formatDate(LocalDateTime.now()));
}
metadata.setMessageCount(messageCount);
metadata.setUpdatedAt(LocalDateTime.now());
saveMetadata(metadata);
}
private String formatDate(LocalDateTime dateTime) {
return dateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
}
}