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

相关推荐
两个蝴蝶飞4 小时前
Java量化系列(四):实现自选股票维护功能
java·经验分享
短剑重铸之日6 小时前
7天读懂MySQL|Day 5:执行引擎与SQL优化
java·数据库·sql·mysql·架构
冰西瓜6006 小时前
从项目入手机器学习——鸢尾花分类
人工智能·机器学习·分类·数据挖掘
爱思德学术6 小时前
中国计算机学会(CCF)推荐学术会议-C(人工智能):IJCNN 2026
人工智能·神经网络·机器学习
酒九鸠玖6 小时前
Java--多线程
java
Dreamboat-L6 小时前
云服务器上部署nginx
java·服务器·nginx
偶信科技6 小时前
国产极细拖曳线列阵:16mm“水下之耳”如何撬动智慧海洋新蓝海?
人工智能·科技·偶信科技·海洋设备·极细拖曳线列阵
长安er6 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
Java后端的Ai之路6 小时前
【神经网络基础】-神经网络学习全过程(大白话版)
人工智能·深度学习·神经网络·学习
庚昀◟7 小时前
用AI来“造AI”!Nexent部署本地智能体的沉浸式体验
人工智能·ai·nlp·持续部署