MessageChatMemoryAdvisor adds conversational memory to a Spring AI ChatClient. It stores user and assistant dialogue through ChatMemory and replays earlier turns as distinct role-based messages in later prompts, allowing follow-up questions to retain context. section 5.1 section 5.2.2
Configure the advisor by:
- Passing a ChatMemory instance to MessageChatMemoryAdvisor.builder(chatMemory).build(). section 5.2.1
- Registering the resulting advisor with ChatClient.Builder.defaultAdvisors(), alongside advisors such as QuestionAnswerAdvisor. section 5.2.1
- Using the default MessageWindowChatMemory, whose in-memory repository keeps history in a Map and loses it when the application restarts. section 5.2.1
For a new conversation, the prompt contains the current user message. After a response, subsequent prompts include the earlier user message, assistant answer, and new user message as separate entries. Each turn therefore extends the messages collection. section 5.2.2
Clarifying a Burger Battle question
After asking “What is the Burger Force Field card?”, a user can ask “Does it protect against Burgerpocalypse?” The advisor replays the earlier exchange so the pronoun “it” remains interpretable; the demonstrated answer is no. section 5.2 section 5.2.1
Listing 5.1 Adding message-oriented chat memory as a default advisor
@Bean
ChatClient chatClient(
ChatClient.Builder chatClientBuilder,
VectorStore vectorStore,
ChatMemory chatMemory) {
return chatClientBuilder
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(chatMemory).build(), #1
QuestionAnswerAdvisor.builder(vectorStore)
.searchRequest(SearchRequest.builder().build()).build())
.build();
}
The configuration listing shows MessageChatMemoryAdvisor registered as a default ChatClient advisor beside QuestionAnswerAdvisor. section 5.2.1
