使用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可以记住我的名字

相关推荐
法外狂徒14 分钟前
将 Pi Agent 接入 HagiCode 的实践之路
服务器·前端·人工智能
CoderIsArt5 分钟前
使用深度学习方法进行纺织品和颜色缺陷检测
人工智能·深度学习
木木学AI5 分钟前
2026年云呼叫中心PoC验证:通信底座、高并发、工单集成三维评估方法
人工智能
hongyucai7 分钟前
详解rlinf强化学习四步曲
人工智能·python·算法·架构
c_lb72887 分钟前
2026年下半年AI量化工具,阶段不同重点也不同
人工智能·python
IT_陈寒11 分钟前
React中useEffect的依赖项把我坑惨了
前端·人工智能·后端
北京阿法龙科技有限公司16 分钟前
AR智能眼镜安防应用核心指标:识别距离筑牢防线
java·开发语言·ar
a11177618 分钟前
SLAM 学习笔记(三)视觉里程计2(VO) 特征点法
人工智能·笔记·学习
湘美书院--湘美谈教育19 分钟前
湘美谈教育湘美书院绥宁文学系列:AI时代的小说,雪峰号
大数据·人工智能·深度学习·机器学习·生活
殘殤血23 分钟前
Tomcat的事件监听机制:观察者模式 _
java·观察者模式·tomcat