图片预览

滚轮缩放 · 拖动移动 · Esc 关闭

Skip to content

AI 聊天历史持久化设计文档 ​

概述 ​

本文档描述了 ai_chat_history 表的设计以及如何与 BasicChatbotAgent 集成,实现聊天历史的持久化存储。

数据库设计 ​

表结构: ai_chat_history ​

sql
CREATE TABLE `ai_chat_history`
(
    `session_id`     VARCHAR(128)     NOT NULL COMMENT '会话ID - 主键',
    `agent_id`       BIGINT           NULL COMMENT 'Agent ID',
    `agent_uid`      VARCHAR(32)      NULL COMMENT 'Agent UID',
    `user_id`        VARCHAR(64)      NULL COMMENT '用户ID',
    `username`       VARCHAR(64)      NULL COMMENT '用户名称',
    `messages`       LONGTEXT         NULL COMMENT '消息历史JSON',
    `message_count`  INT DEFAULT 0    NULL COMMENT '消息总数',
    `first_message`  TEXT             NULL COMMENT '首次消息',
    `session_title`  VARCHAR(255)     NULL COMMENT '会话标题',
    `session_status` VARCHAR(20)      NULL COMMENT '会话状态',
    `create_by`      VARCHAR(64)      NULL,
    `create_time`    DATETIME         NULL,
    `update_by`      VARCHAR(64)      NULL,
    `update_time`    DATETIME         NULL,
    `del_flag`       CHAR DEFAULT '0' NULL,
    `tenant_id`      BIGINT           NULL,
    PRIMARY KEY (`session_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

设计理念 ​

  1. sessionId 作为主键: 每个会话有唯一标识,支持会话级别的历史管理
  2. JSON 存储消息: 使用 messages 字段存储完整的对话消息列表(JSON 格式)
  3. 元数据管理: 记录 agentId, userId, 消息数量等元数据
  4. 会话状态: 支持 active/closed/archived 等状态管理
  5. 多索引支持: 支持按 agent_id, user_id, 时间等多维度查询

架构组件 ​

1. Entity 层 ​

  • AiChatHistoryEntity: 实体类,使用 MyBatis-Plus 注解
  • 使用 JacksonTypeHandler 自动序列化 List<ChatMessage> 为 JSON

2. Mapper 层 ​

  • AiChatHistoryMapper: MyBatis Mapper 接口
  • AiChatHistoryMapper.xml: MyBatis 映射文件

3. Service 层 ​

  • AiChatHistoryService: 服务接口
  • AiChatHistoryServiceImpl: 服务实现

主要功能:

  • 保存/更新会话历史
  • 查询会话历史(按 sessionId, userId, agentId)
  • 清除/删除会话历史
  • 更新会话标题和状态

4. ChatMemoryStore 实现 ​

  • AiChatHistoryChatMemoryStore: 实现 LangChain4j 的 ChatMemoryStore 接口
  • 将 ChatMemory 持久化到 ai_chat_history 表

5. 集成适配器 ​

  • BasicChatbotAgentAdapter: 提供便捷的集成接口
  • 自动管理会话创建、历史查询等功能

使用方式 ​

方式一: 使用 BasicChatbotAgentAdapter (推荐) ​

java
@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private BasicChatbotAgentAdapter chatAdapter;

    // 1. 创建新会话
    @PostMapping("/session/new")
    public String createSession(@RequestParam Long agentId) {
        return chatAdapter.createNewSession(agentId);
    }

    // 2. 执行对话(自动持久化)
    @PostMapping("/message")
    public String chat(@RequestParam Long agentId,
                       @RequestParam String message,
                       @RequestParam String sessionId) {
        return chatAdapter.chatWithHistory(agentId, message, sessionId);
    }

    // 3. 查询历史会话列表
    @GetMapping("/history/list")
    public List<AiChatHistoryEntity> getHistoryList() {
        return chatAdapter.getUserHistoryList();
    }

    // 4. 删除会话
    @DeleteMapping("/session/{sessionId}")
    public boolean deleteSession(@PathVariable String sessionId) {
        return chatAdapter.deleteSession(sessionId);
    }
}

方式二: 手动配置 ChatMemoryStore ​

java
@Service
public class CustomChatService {

    @Autowired
    private AiChatHistoryChatMemoryStore chatMemoryStore;

    @Autowired
    private StreamingChatModelFactory streamingChatModelFactory;

    public String chat(String sessionId, String message) {
        // 1. 创建持久化的 ChatMemory
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
            .id(sessionId)
            .maxMessages(10)
            .chatMemoryStore(chatMemoryStore)  // 使用持久化存储
            .build();

        // 2. 添加用户消息
        chatMemory.add(UserMessage.from(message));

        // 3. 获取 ChatModel
        StreamingChatModel chatModel = streamingChatModelFactory
            .build(ChatLanguageModelConfig.builder().build());

        // 4. 执行对话
        // ... (执行对话逻辑)

        return response;
    }
}

方式三: 直接使用 Service 层 ​

java
@Service
public class HistoryQueryService {

    @Autowired
    private AiChatHistoryService chatHistoryService;

    // 查询用户的所有会话
    public List<AiChatHistoryEntity> getUserSessions(String userId) {
        return chatHistoryService.listByUserId(userId);
    }

    // 查询某个会话的消息列表
    public List<ChatMessage> getSessionMessages(String sessionId) {
        return chatHistoryService.getMessagesBySessionId(sessionId);
    }

    // 手动保存会话历史
    public void saveHistory(String sessionId, Long agentId,
                           String userId, List<ChatMessage> messages) {
        chatHistoryService.saveOrUpdateHistory(
            sessionId, agentId, null, userId, messages
        );
    }
}

与 BasicChatbotAgent 的集成 ​

自动集成 ​

BasicChatbotAgent 默认使用 ChatMemoryAdvisorProvider 管理 ChatMemory。要启用持久化:

  1. 修改 ChatMemoryAdvisorProvider 配置,使用 AiChatHistoryChatMemoryStore
  2. 或者使用 BasicChatbotAgentAdapter,它会自动处理持久化

工作流程 ​

用户请求
    ↓
BasicChatbotAgentAdapter.chatWithHistory()
    ↓
BasicChatbotAgent.chat()
    ↓
ChatMemory (使用 AiChatHistoryChatMemoryStore)
    ↓
自动保存到 ai_chat_history 表

数据流 ​

写入流程 ​

  1. 用户发送消息
  2. BasicChatbotAgent 将消息添加到 ChatMemory
  3. ChatMemory 调用 ChatMemoryStore.updateMessages()
  4. AiChatHistoryChatMemoryStore 将消息保存到数据库

读取流程 ​

  1. BasicChatbotAgent 创建 ChatMemory
  2. ChatMemory 调用 ChatMemoryStore.getMessages()
  3. AiChatHistoryChatMemoryStore 从数据库读取历史消息
  4. 历史消息被恢复到 ChatMemory

注意事项 ​

1. sessionId 管理 ​

  • sessionId 应该在会话开始时生成并保持不变
  • 推荐使用 UUID 作为 sessionId: IdUtil.simpleUUID()
  • 前端需要保存 sessionId 用于后续对话

2. 性能优化 ​

  • messages 字段使用 LONGTEXT,支持大量消息存储
  • 建议定期归档或清理历史会话
  • 考虑使用消息窗口限制(maxMessages)避免单次查询过大

3. 安全性 ​

  • 确保 userId 验证,防止跨用户访问
  • 支持租户隔离(tenantId)
  • 删除操作使用软删除(del_flag)

4. 扩展性 ​

  • 可以添加自定义元数据字段
  • 支持会话标题、状态等扩展属性
  • 可以实现会话分享、导出等功能

文件清单 ​

数据库 ​

  • db/ai_chat_history.sql - 建表 SQL

实体层 ​

  • domain/entity/AiChatHistoryEntity.java - 实体类

Mapper 层 ​

  • mapper/AiChatHistoryMapper.java - Mapper 接口
  • resources/mapper/AiChatHistoryMapper.xml - Mapper XML

Service 层 ​

  • service/AiChatHistoryService.java - Service 接口
  • service/impl/AiChatHistoryServiceImpl.java - Service 实现

集成层 ​

  • llm/chatMemory/AiChatHistoryChatMemoryStore.java - ChatMemoryStore 实现
  • agent/chatbot/BasicChatbotAgentAdapter.java - 集成适配器

测试建议 ​

单元测试 ​

java
@SpringBootTest
public class AiChatHistoryServiceTest {

    @Autowired
    private AiChatHistoryService chatHistoryService;

    @Test
    public void testSaveAndQuery() {
        // 1. 保存会话历史
        List<ChatMessage> messages = Arrays.asList(
            UserMessage.from("你好"),
            AiMessage.from("你好!有什么可以帮助你的吗?")
        );

        chatHistoryService.saveOrUpdateHistory(
            "test-session-001", 1L, "agent-001", "user-001", messages
        );

        // 2. 查询会话历史
        AiChatHistoryEntity history = chatHistoryService
            .getHistoryBySessionId("test-session-001");

        assertNotNull(history);
        assertEquals(2, history.getMessageCount());
        assertEquals("你好", history.getFirstMessage());
    }
}

集成测试 ​

java
@SpringBootTest
public class BasicChatbotAgentAdapterTest {

    @Autowired
    private BasicChatbotAgentAdapter chatAdapter;

    @Test
    public void testChatWithHistory() {
        // 1. 创建会话
        String sessionId = chatAdapter.createNewSession(1L);

        // 2. 第一轮对话
        String response1 = chatAdapter.chatWithHistory(
            1L, "我叫小明", sessionId
        );

        // 3. 第二轮对话(验证记忆)
        String response2 = chatAdapter.chatWithHistory(
            1L, "我叫什么名字?", sessionId
        );

        assertTrue(response2.contains("小明"));
    }
}

总结 ​

本设计实现了:

  1. ✅ 完整的聊天历史持久化存储
  2. ✅ 与 BasicChatbotAgent 的无缝集成
  3. ✅ 灵活的查询和管理接口
  4. ✅ 支持多租户和安全性
  5. ✅ 易于使用的适配器模式

通过 BasicChatbotAgentAdapter,开发者可以用几行代码实现完整的聊天历史功能,无需关心底层实现细节。