Spring AI Alibaba 对话记忆使用

一、对话记忆 (ChatMemory)简介

1、对话记忆介绍

"大模型的对话记忆"这一概念,根植于人工智能与自然语言处理领域,特别是针对具有深度学习能力的大型语言模型而言,它指的是模型在与用户进行交互式对话过程中,能够追踪、理解并利用先前对话上下文的能力。

此机制使得大模型不仅能够响应即时的输入请求,还能基于之前的交流内容能够在对话中记住先前的对话内容,并根据这些信息进行后续的响应。

这种记忆机制使得模型能够在对话中持续跟踪和理解用户的意图和上下文,从而实现更自然和连贯的对话。

2、基于memory的对话记忆

spring-ai-alibaba支持基于chat memory的对话记忆,也就是不需要调用显示的记录每一轮的对话历史。而是将对话的上下文内容进行存储和记录。

开发者可以自行实现ChatMemory基于类似于文件、内存,MySQL,Redis等方式进行上下文内容的存储和记录。

二、对话记忆 (ChatMemory)使用

Spring AI Alibaba 对话记忆 (ChatMemory):https://java2ai.com/docs/1.0.0-M6.1/tutorials/memory/

Spring AI Alibaba 支持以上 Model 抽象与通义系列模型的适配,并通过 spring-ai-alibaba-starter AutoConfiguration 自动初始化了默认实例,因此我们可以在应用程序中直接注入 ChatModel、ImageModel 等 bean,当然在需要的时候也可以自定义 Model 实例。

1、基于内存存储的对话记忆实现

在普通 Controller Bean 中注入 ChatMemory 实例,实现下面几个功能:

  • 简单调用
  • 流式调用

由于 InMemoryChatMemory是内置支持,所以我们直接使用它。

编写 Controller接口

java 复制代码
/**
 * 基于内存的对话记忆
 */
@Slf4j
@RestController
@RequestMapping("/dashscope/chat-memory/inMemory")
public class DashScopeMemoryInMemoryController {

    //初始化基于内存的对话记忆
    private ChatMemory chatMemory = new InMemoryChatMemory();

    private final ChatClient dashScopeChatClient;

    public DashScopeMemoryInMemoryController(ChatModel chatModel) {
        this.dashScopeChatClient = ChatClient.builder(chatModel)
                .build();
    }

    /**
     * 获取对话的唯一标识接口
     */
    @GetMapping("/getChatId")
    public String getChatId() {
        //对话记忆的唯一标识
        String chatId = UuidUtils.generateUuid();
        return chatId;
    }


    /**
     * 简单调用
     */
    @GetMapping("/simple/chat")
    public String simpleChat(@RequestParam(defaultValue = "你好,介绍下你自己!") String userInputPrompt,
                             @RequestParam("chatId") String chatId) {
        //对话记忆的唯一标识
        if (StringUtils.isBlank(chatId)) {
            return "chatId is null";
        }

        String aiOutput = dashScopeChatClient.prompt(userInputPrompt).advisors(
                new MessageChatMemoryAdvisor(chatMemory)
        ).advisors(
                a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)
        ).call().content();

        log.info("simpleChat --> userInputPrompt = {}", userInputPrompt);
        return aiOutput;
    }

    /**
     * 流式调用。
     * 可以使大模型的输出信息实现打字机效果。
     */
    @GetMapping("/stream/chat")
    public Flux<String> streamChat(HttpServletResponse response,
                                   @RequestParam(defaultValue = "你好,介绍下你自己!") String userInputPrompt,
                                   @RequestParam("chatId") String chatId) {

        // 避免接口返回乱码
        response.setCharacterEncoding("UTF-8");

        log.info("streamChat --> userInputPrompt ={}", userInputPrompt);
        Flux<String> aiOutput = dashScopeChatClient.prompt(userInputPrompt).advisors(
                new MessageChatMemoryAdvisor(chatMemory)
        ).advisors(
                a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)
        ).stream().content();
        return aiOutput;
    }

}

启动项目,访问接口与 AI 大模型智能对话。

我们获取到对话id之后,进行下面多轮的对话,对话记忆机制生效。

  1. 你是一个旅游规划师
  2. 我想去西安
  3. 能帮我推荐一些旅游景点吗?
  4. 那里的美食如何?
  5. 那里有什么样的历史文化?


基于 MySQL,Redis等方式进行上下文内容的存储和记录,需要我们引入官方依赖,然后将 InMemoryChatMemory替换为对应的MySQL,Redis方式并配置连接信息。

-- 求知若饥,虚心若愚。

相关推荐
神云瑟瑟21 小时前
spring ai对接deepseek
spring ai·deepseek
callJJ1 天前
Spring AI 文本聊天模型完全指南:ChatModel 与 ChatClient
java·大数据·人工智能·spring·spring ai·聊天模型
hay_lee2 天前
Spring AI实现对话聊天-流式输出
java·人工智能·ollama·spring ai
要开心吖ZSH5 天前
Spring AI Alibaba 个人学习笔记
人工智能·学习·spring·spring ai·springaialibaba
库里不会投三分5 天前
谢飞机面试记:从JVM到Spring AI的3轮灵魂拷问(音视频+AI招聘双场景)
spring cloud·java面试·rag·spring ai·ai招聘·音视频架构
猿小羽6 天前
基于 Spring AI 与 Streamable HTTP 构建 MCP Server 实践
java·llm·spring ai·mcp·streamable http
没有腰的嘟嘟嘟6 天前
[特殊字符] 本地部署 Qwen3:4B 大模型并使用 Spring Boot 对接实践指南
spring·ai·spring ai
猿小羽13 天前
AI 2.0 时代全栈开发实战:从 Spring AI 到 MLOps 的进阶指南
ai·llm·mlops·rag·vector database·spring ai·prompt engineering
猿小羽13 天前
AI 学习与实战系列:Spring AI + MCP 深度实战——构建标准化、可扩展的智能 Agent 系统
java·spring boot·llm·agent·spring ai·mcp·model context protocol
猿小羽13 天前
深度实战:Spring AI 与 MCP(Model Context Protocol)构建下一代 AI Agent
java·大模型·llm·ai agent·spring ai·开发者工具·mcp