Spring Ai Chat Memory
在前面的文章讲述如何使用各种各样的大模型进行智能对话,但通过实践我们发现大模型不能上下文关联,比如我第一次告诉它我叫张三,第二次问它我叫什么,它还是不知道。chat memory就是Spring ai提供的解决方案。本文主要简述提供的内存Memory、Advisor实现chat memory、jdbc存储chat memory和Redis存储chat memory。
什么是Chat memory
官方解释:
Large language models (LLMs) are stateless, meaning they do not retain information about previous interactions. This can be a limitation when you want to maintain context or state across multiple interactions. To address this, Spring AI provides chat memory features that allow you to store and retrieve information across multiple interactions with the LLM.
以上翻译就是说:大模型是一种无状态的,意味着不会保存之前对话的信息。当你想使用上下文信息实现多轮多花就产生了限制,为了解决这一问题,spring ai 就提供了chat memory 整个类别,允许你保存多轮对话信息。
Chat Memory和Chat History的区别
官方解释:
Chat Memory. The information that a large-language model retains and uses to maintain contextual awareness throughout a conversation.
Chat History. The entire conversation history, including all messages exchanged between the user and the model.
上面的官方解释,重要区分点就是chat memory表示一次会话的上下文对话记录;history memory表示所有的会话历史;
Chat memory的使用
在使用之前,我们首先需要做的是引入chat memory的依赖,如下:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-memory</artifactId>
</dependency>
1.MessageWindowChatMemory
MessageWindowChatMemory是sping ai提供的内置对象,存储在内存中。存储在 Map<String, List<Message>> chatMemoryStore = new ConcurrentHashMap(),底层调用saveAll方法完成新增,conversationId 表示会话的id,包含多轮对话。如下图源码所示:

具体使用方法如下代码所示:
@Test
public void testReReadAdvisor1(){
ChatClient client = ChatClient.builder(deepSeekChatModel)
// defaultAdvisors(new SimpleLoggerAdvisor())//SafeGuardAdvisor 敏感词定义,若出现敏感词中断
.build();
MessageWindowChatMemory memory = MessageWindowChatMemory.builder().build();
String conversionId="20250512180601";
UserMessage userMessage = new UserMessage("我叫张三");
memory.add(conversionId,userMessage);
System.out.println("question1:我叫张三");
String response1 = client.prompt(new Prompt(memory.get(conversionId))).call().content();
System.out.println("round1:"+response1);
memory.add(conversionId,new UserMessage(response1));
UserMessage reponseMessage = new UserMessage("我叫什么");
System.out.println("question2:我叫什么");
memory.add(conversionId,reponseMessage);
St

最低0.47元/天 解锁文章
1168

被折叠的 条评论
为什么被折叠?



