An advisor is a Spring AI component that intercepts a ChatClient interaction before and after model execution. It can inspect or modify the request, add prompt context, and extract information from the response. section 4.4.2 section 4.5
Advisors move recurring interaction logic out of application services. QuestionAnswerAdvisor searches a vector store for documents similar to the user's question, appends context and instructions to the prompt, and leaves the service focused on the application request. section 4.5
Spring AI provides advisors for several interaction concerns:
- QuestionAnswerAdvisor performs retrieval-augmented generation by adding similar document chunks to the prompt. section 4.5
- MessageChatMemoryAdvisor adds stored history as separate user and assistant messages. section 5.1
- PromptChatMemoryAdvisor injects history as one string in a system-message template. section 5.1
- VectorStoreChatMemoryAdvisor retrieves conversation snippets from a vector store by similarity. section 5.1
- SafeGuardAdvisor and custom advisors help intercept malicious questions and responses, although they are not complete defenses. section 10.3 section 10.5
Applying retrieval with an advisor
Attach QuestionAnswerAdvisor to a ChatClient prompt with .advisors(QuestionAnswerAdvisor.builder(vectorStore).build()). The advisor retrieves relevant game rules and adds them to the interaction. Configure it as a default advisor on the ChatClient when the behavior should apply broadly, or pass a filter expression when retrieval must match a particular game. section 4.5
Listing 4.3 Configuring a ChatClient bean with a default advisor
package com.example.boardgamebuddy;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore
.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AiConfig {
@Bean
ChatClient chatClient(
ChatClient.Builder chatClientBuilder, VectorStore vectorStore) {
return chatClientBuilder
.defaultAdvisors(
QuestionAnswerAdvisor.builder(vectorStore).build())
.build();
}
}
A Java configuration listing shows how to register QuestionAnswerAdvisor as a ChatClient default advisor. section 4.5
