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

相关推荐
黎雁·泠崖18 分钟前
【魔法森林冒险】1/14 项目总览:用Java打造你的第一个回合制冒险游戏
java·开发语言
NuageL25 分钟前
原始Json字符串转化为Java对象列表/把中文键名变成英文键名
java·spring boot·json
人机与认知实验室27 分钟前
一些容易被人工智能取代的职业
人工智能
茶栀(*´I`*)31 分钟前
【NLP入门笔记】:自然语言处理基础与文本预处理
人工智能·自然语言处理·nlp
却道天凉_好个秋35 分钟前
Tensorflow数据增强(三):高级裁剪
人工智能·深度学习·tensorflow
222you38 分钟前
Redis的主从复制和哨兵机制
java·开发语言
江湖有缘42 分钟前
零基础入门:使用 Docker 快速部署 Organizr 个人主页
java·服务器·docker
藦卡机器人43 分钟前
国产机械臂做的比较好的品牌有哪些?
大数据·数据库·人工智能
chilavert3181 小时前
技术演进中的开发沉思-357:重排序(下)
java·后端
Boop_wu1 小时前
Spring生态
java·后端·spring