使用Spring-AI的chatMemoryAdvisor实现多轮会话

代码

controller/ZhipuChatMemoryController.java

java 复制代码
package org.example.controller;

import org.example.advisor.CallAdvisor1;
import org.example.advisor.CallAdvisor2;
import org.example.advisor.SimpleMessageChatMemoryAdvisor;
import org.example.entity.Book;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.zhipuai.ZhiPuAiChatOptions;
import org.springframework.web.bind.annotation.GetMapping;
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("/chatMemory")
public class ZhipuChatMemoryController {

    // 声明 ChatClient 实例,用于与 AI 模型进行交互
    private final ChatClient chatClient;

    /**
     * 构造函数,初始化 ChatClient 并配置聊天内存顾问
     * @param builder ChatClient.Builder 实例,用于构建 ChatClient
     */
    public ZhipuChatMemoryController(ChatClient.Builder builder) {

        // 创建 MessageWindowChatMemory,用于管理对话历史消息窗口
        MessageWindowChatMemory windowChatMemory = MessageWindowChatMemory.builder()
                .build();
        // 创建 MessageChatMemoryAdvisor,用于管理对话内存
        MessageChatMemoryAdvisor chatMemoryAdvisor = MessageChatMemoryAdvisor.builder(windowChatMemory)
                .build();

        // 构建 ChatClient,设置默认Advisors
        this.chatClient = builder
                .defaultAdvisors(chatMemoryAdvisor)
                .build();
    }

    /**
     * 处理聊天请求
     * @param question 用户问题
     * @param sessionId 会话ID,用于区分不同用户的对话上下文
     * @return AI 模型的响应内容
     */
    @GetMapping("/messageChatMemoryAdvisor")
    public String messageChatMemoryAdvisor(@RequestParam(name = "question") String question,
                                           @RequestParam(name = "sessionId") String sessionId) {

        String content = chatClient.prompt()
                .user(question)
                // 把会话ID存入上下文,确保对话记忆与特定会话关联
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, sessionId))
                .call()
                .content();
        return content;
    }
}

效果

AI可以记住我的名字

相关推荐
戴西软件5 小时前
戴西iDWS.3DViz Suite数据轻量化可视化软件,从传统桌面软件向云端协同的重大突破
大数据·运维·网络·人工智能·机器学习·3d
AIkk865 小时前
2026年AI证件照工具功能速览:三款实用方案对比
人工智能
ReleaseU5 小时前
Harness + MCP:打通企业工具链的最后一步
人工智能·大模型
衡石科技6 小时前
衡石科技携手超聚变联合发布HENGSHI BOX,引领私域ChatBI规模化落地
大数据·人工智能·科技
花间相见6 小时前
【LangChain组件03】—— LangChain Agents 执行与状态:工作流程与状态管理实战
java·前端·langchain
敲代码的嘎仔6 小时前
28届后端开发-海康威视日常实习一面(已OC)
java·开发语言·后端·面试·海康威视·实习·大厂
新知图书6 小时前
10.4 交互优化与用户体验提升
人工智能·多模态·智能体
IT_陈寒6 小时前
JavaScript数组排序踩的坑,差点让我加班到凌晨
前端·人工智能·后端
敢敢是只喵i6 小时前
一个本地 AI Agent 要操作多个门店或 SaaS 账号,应该怎样安全切换身份?
人工智能·安全·ai·系统架构·业界资讯