Spring Boot auto-configuration for chat memory functionality in Spring AI applications
This file contains the comprehensive API documentation for all Spring AI Chat Memory components.
Note: This is a detailed reference document. For quick start, see Quick Start Guide.
The core interface for storing and managing conversation memory.
public interface ChatMemory {
String DEFAULT_CONVERSATION_ID = "default";
String CONVERSATION_ID = "chat_memory_conversation_id";
void add(String conversationId, Message message);
void add(String conversationId, List<Message> messages);
List<Message> get(String conversationId);
void clear(String conversationId);
}Package: org.springframework.ai.chat.memory
Constants:
DEFAULT_CONVERSATION_ID: Default conversation identifier ("default")CONVERSATION_ID: Context key for retrieving conversation ID ("chat_memory_conversation_id")Methods:
Adds a single message to the specified conversation.
conversationId (String): Unique identifier for the conversation (must not be null or empty)message (Message): The message to add (must not be null)add(conversationId, List.of(message))Adds multiple messages to the specified conversation.
conversationId (String): Unique identifier for the conversation (must not be null or empty)messages (List<Message>): List of messages to add (must not be null, cannot contain null elements)Retrieves all messages for the specified conversation.
conversationId (String): Unique identifier for the conversation (must not be null or empty)Removes all messages for the specified conversation.
conversationId (String): Unique identifier for the conversation (must not be null or empty)Thread Safety: Implementations should be thread-safe for concurrent access.
Repository interface for persisting and retrieving chat messages.
public interface ChatMemoryRepository {
List<String> findConversationIds();
List<Message> findByConversationId(String conversationId);
void saveAll(String conversationId, List<Message> messages);
void deleteByConversationId(String conversationId);
}Package: org.springframework.ai.chat.memory
Methods:
Retrieves all conversation IDs stored in the repository.
Finds all messages for a given conversation.
conversationId (String): Unique identifier for the conversationReplaces all existing messages for the conversation with the provided messages.
conversationId (String): Unique identifier for the conversationmessages (List<Message>): Messages to save (replacing existing messages)Deletes all messages for a given conversation.
conversationId (String): Unique identifier for the conversationA ChatMemory implementation that maintains a sliding window of recent messages with special handling for system messages.
public final class MessageWindowChatMemory implements ChatMemory {
public static Builder builder();
@Override
public void add(String conversationId, List<Message> messages);
@Override
public List<Message> get(String conversationId);
@Override
public void clear(String conversationId);
}Package: org.springframework.ai.chat.memory
Description: Maintains a message window of specified size, automatically evicting older messages when the limit is exceeded. System messages receive special treatment:
SystemMessage is added, all previous SystemMessage instances are removedSystemMessage instances are preserved while other message types are evicted firstDefault Configuration: The default maximum messages is 20 when using the builder without specifying maxMessages.
Factory Method:
builder(): Returns a Builder instance for constructing MessageWindowChatMemoryBehavior:
Default implementation of ChatMemoryRepository using an in-memory concurrent map.
public final class InMemoryChatMemoryRepository implements ChatMemoryRepository {
public InMemoryChatMemoryRepository();
@Override
public List<String> findConversationIds();
@Override
public List<Message> findByConversationId(String conversationId);
@Override
public void saveAll(String conversationId, List<Message> messages);
@Override
public void deleteByConversationId(String conversationId);
}Package: org.springframework.ai.chat.memory
Description: Thread-safe in-memory implementation using ConcurrentHashMap for storage. Suitable for development and testing but not recommended for production as data is lost on application restart.
Constructor:
InMemoryChatMemoryRepository(): Creates a new in-memory repository with an empty storeImplementation Notes:
Map<String, List<Message>> structurefindByConversationId() returns a copy of the stored list to prevent external modificationfindConversationIds() returns a new list of all conversation IDsConcurrentHashMapData Loss Warning: All data is lost when the application restarts. For production use, implement a persistent ChatMemoryRepository or use one of the provided persistent implementations.
public interface Message extends Content {
MessageType getMessageType();
}Package: org.springframework.ai.chat.messages
Extends: org.springframework.ai.content.Content
Methods:
getMessageType(): Returns the type of this message (USER, ASSISTANT, SYSTEM, or TOOL)public enum MessageType {
USER("user"),
ASSISTANT("assistant"),
SYSTEM("system"),
TOOL("tool");
public static MessageType fromValue(String value);
public String getValue();
}Package: org.springframework.ai.chat.messages
Enum Constants:
USER: Messages from end-users or developersASSISTANT: Messages generated by the AI assistantSYSTEM: High-level instructions for the conversationTOOL: Function/tool responsesMethods:
fromValue(String value): Converts a string value to MessageType
getValue(): Returns the string value of the message typepublic class UserMessage extends AbstractMessage implements MediaContent {
public UserMessage(String textContent);
public UserMessage(Resource resource);
@Override
public String getText();
@Override
public List<Media> getMedia();
public UserMessage copy();
public Builder mutate();
public static Builder builder();
}Package: org.springframework.ai.chat.messages
Constructors:
UserMessage(String textContent): Creates a user message with text content
UserMessage(Resource resource): Creates a user message from a Spring Resource
Methods:
getText(): Returns the message textgetMedia(): Returns attached media (empty list if no media)copy(): Creates a copy of this messagemutate(): Creates a builder initialized with this message's databuilder(): Creates a new builder instance (static)UserMessage.Builder:
public static final class Builder {
public Builder text(String textContent);
public Builder text(Resource resource);
public Builder media(List<Media> media);
public Builder media(Media... media);
public Builder metadata(Map<String, Object> metadata);
public UserMessage build();
}public class AssistantMessage extends AbstractMessage implements MediaContent {
public AssistantMessage(String content);
public List<ToolCall> getToolCalls();
public boolean hasToolCalls();
@Override
public List<Media> getMedia();
public static Builder builder();
}Package: org.springframework.ai.chat.messages
Constructors:
AssistantMessage(String content): Creates assistant message with text contentMethods:
getToolCalls(): Returns tool calls made by the assistant (empty list if none)hasToolCalls(): Checks if message contains tool callsgetMedia(): Returns attached media (empty list if no media)builder(): Creates a new builder instance (static)AssistantMessage.ToolCall Record:
public record ToolCall(String id, String type, String name, String arguments) {
}Components:
id (String): Unique identifier for the tool calltype (String): Type of the tool callname (String): Name of the tool/functionarguments (String): Arguments passed to the tool (typically JSON string)public class SystemMessage extends AbstractMessage {
public SystemMessage(String textContent);
public SystemMessage(Resource resource);
@Override
public String getText();
public SystemMessage copy();
public Builder mutate();
public static Builder builder();
}Package: org.springframework.ai.chat.messages
Description: System-level instructions for the conversation. Treated specially by MessageWindowChatMemory (preserved during eviction, replaced when new system messages are added).
Constructors:
SystemMessage(String textContent): Creates system message with text content
SystemMessage(Resource resource): Creates system message from a Spring Resource
public class ToolResponseMessage extends AbstractMessage {
public static Builder builder();
public List<ToolResponse> getResponses();
}Package: org.springframework.ai.chat.messages
Description: Represents responses from tool/function executions.
Methods:
builder(): Creates a new builder instancegetResponses(): Returns the list of tool responsesToolResponseMessage.ToolResponse Record:
public record ToolResponse(String id, String name, String responseData) {
}Components:
id (String): Identifier matching the tool call idname (String): Name of the tool that was executedresponseData (String): Data returned by the tool executionpublic final class JdbcChatMemoryRepository implements ChatMemoryRepository {
public static Builder builder();
}Package: org.springframework.ai.chat.memory.repository.jdbc
Maven Artifact: spring-ai-model-chat-memory-repository-jdbc
JdbcChatMemoryRepository.Builder:
public static final class Builder {
public Builder jdbcTemplate(JdbcTemplate jdbcTemplate);
public Builder dialect(JdbcChatMemoryRepositoryDialect dialect);
public Builder dataSource(DataSource dataSource);
public Builder transactionManager(PlatformTransactionManager txManager);
public JdbcChatMemoryRepository build();
}Methods:
jdbcTemplate(JdbcTemplate): Sets the JDBC template (required)
dialect(JdbcChatMemoryRepositoryDialect): Sets the database dialect
dataSource(DataSource): Sets the data source for auto-detecting the dialecttransactionManager(PlatformTransactionManager): Sets the transaction manager (optional)build(): Constructs the JdbcChatMemoryRepository instance
Supported Databases: PostgreSQL, MySQL, MariaDB, SQL Server, H2, HSQLDB, SQLite, Oracle
public final class MongoChatMemoryRepository implements ChatMemoryRepository {
public static Builder builder();
}Package: org.springframework.ai.chat.memory.repository.mongo
Maven Artifact: spring-ai-model-chat-memory-repository-mongodb
MongoChatMemoryRepository.Builder:
public static final class Builder {
public Builder mongoTemplate(MongoTemplate mongoTemplate);
public MongoChatMemoryRepository build();
}Methods:
mongoTemplate(MongoTemplate): Sets the Spring Data MongoDB template (required)
build(): Constructs the MongoChatMemoryRepository instance
public final class CassandraChatMemoryRepository implements ChatMemoryRepository {
public static final String CONVERSATION_TS = "CassandraChatMemoryRepository_message_timestamp";
public static CassandraChatMemoryRepository create(CassandraChatMemoryRepositoryConfig conf);
}Package: org.springframework.ai.chat.memory.repository.cassandra
Maven Artifact: spring-ai-model-chat-memory-repository-cassandra
Constants:
CONVERSATION_TS: Metadata key for message timestampFactory Method:
create(CassandraChatMemoryRepositoryConfig): Creates a new repository with the provided configuration
public final class Neo4jChatMemoryRepository implements ChatMemoryRepository {
public Neo4jChatMemoryRepository(Neo4jChatMemoryRepositoryConfig config);
public Neo4jChatMemoryRepositoryConfig getConfig();
}Package: org.springframework.ai.chat.memory.repository.neo4j
Maven Artifact: spring-ai-model-chat-memory-repository-neo4j
Constructor:
Neo4jChatMemoryRepository(Neo4jChatMemoryRepositoryConfig): Creates a new repository
public final class CosmosDBChatMemoryRepository implements ChatMemoryRepository {
public static final String CONVERSATION_TS = "conversationTimestamp";
public static CosmosDBChatMemoryRepository create(CosmosDBChatMemoryRepositoryConfig config);
}Package: org.springframework.ai.chat.memory.repository.cosmosdb
Maven Artifact: spring-ai-model-chat-memory-repository-cosmos-db
Constants:
CONVERSATION_TS: Field name for conversation timestampFactory Method:
create(CosmosDBChatMemoryRepositoryConfig): Creates a new repository
public static final class Builder {
public Builder chatMemoryRepository(ChatMemoryRepository chatMemoryRepository);
public Builder maxMessages(int maxMessages);
public MessageWindowChatMemory build();
}Methods:
chatMemoryRepository(ChatMemoryRepository): Sets the repository for persisting messagesmaxMessages(int): Sets the maximum number of messages to retain (must be > 0, default is 20)
build(): Constructs the MessageWindowChatMemory instance
InMemoryChatMemoryRepository by defaultpublic static final class Builder {
public Builder withCqlSession(CqlSession session);
public Builder withKeyspaceName(String keyspace);
public Builder withTableName(String table);
public Builder withMessagesColumnName(String name);
public Builder withTimeToLive(Duration timeToLive);
public Builder disallowSchemaChanges();
public CassandraChatMemoryRepositoryConfig build();
}Default Values:
public static final class Builder {
public Builder withDriver(Driver driver);
public Builder withSessionLabel(String sessionLabel);
public Builder withMessageLabel(String messageLabel);
public Builder withMetadataLabel(String metadataLabel);
public Builder withToolCallLabel(String toolCallLabel);
public Builder withToolResponseLabel(String toolResponseLabel);
public Builder withMediaLabel(String mediaLabel);
public Neo4jChatMemoryRepositoryConfig build();
}Default Labels:
public static final class Builder {
public Builder withCosmosClient(CosmosAsyncClient cosmosClient);
public Builder withDatabaseName(String databaseName);
public Builder withContainerName(String containerName);
public Builder withPartitionKeyPath(String partitionKeyPath);
public CosmosDBChatMemoryRepositoryConfig build();
}Default Values:
Prefix: spring.ai.chat.memory.repository.jdbc
# Schema initialization
spring.ai.chat.memory.repository.jdbc.initialize-schema=always
# Options: EMBEDDED, ALWAYS, NEVER
# Database platform (auto-detected if not specified)
spring.ai.chat.memory.repository.jdbc.platform=postgresql
# Options: postgresql, mysql, h2, oracle, sqlserver, mariadb, hsqldb, sqlite
# Custom schema location
spring.ai.chat.memory.repository.jdbc.schema=classpath:custom-schema.sqlPrefix: spring.ai.chat.memory.repository.mongo
# Enable automatic index creation
spring.ai.chat.memory.repository.mongo.create-indices=true
# Set time-to-live for conversations
spring.ai.chat.memory.repository.mongo.ttl=PT24H
# Format: ISO-8601 duration (PT1H, P7D, P30D)Prefix: spring.ai.chat.memory.repository.cassandra
# Keyspace configuration
spring.ai.chat.memory.repository.cassandra.keyspace=my_keyspace
# Table configuration
spring.ai.chat.memory.repository.cassandra.table=chat_memory
spring.ai.chat.memory.repository.cassandra.messages-column=messages
# Schema initialization
spring.ai.chat.memory.repository.cassandra.initialize-schema=true
# Time-to-live
spring.ai.chat.memory.repository.cassandra.time-to-live=P30DPrefix: spring.ai.chat.memory.repository.neo4j
# Node label configuration
spring.ai.chat.memory.repository.neo4j.session-label=ChatSession
spring.ai.chat.memory.repository.neo4j.message-label=ChatMessage
spring.ai.chat.memory.repository.neo4j.metadata-label=Metadata
spring.ai.chat.memory.repository.neo4j.tool-call-label=ToolCall
spring.ai.chat.memory.repository.neo4j.tool-response-label=ToolResponse
spring.ai.chat.memory.repository.neo4j.media-label=MediaPrefix: spring.ai.chat.memory.repository.cosmosdb
# Connection configuration
spring.ai.chat.memory.repository.cosmosdb.endpoint=https://myaccount.documents.azure.com:443/
spring.ai.chat.memory.repository.cosmosdb.key=your-account-key
# Connection mode
spring.ai.chat.memory.repository.cosmosdb.connection-mode=direct
# Options: gateway, direct
# Database and container
spring.ai.chat.memory.repository.cosmosdb.database-name=chat_memory_db
spring.ai.chat.memory.repository.cosmosdb.container-name=conversations
# Partition key
spring.ai.chat.memory.repository.cosmosdb.partition-key-path=/conversationId@AutoConfiguration
@ConditionalOnClass({ ChatMemory.class, ChatMemoryRepository.class })
public class ChatMemoryAutoConfiguration {
@Bean
@ConditionalOnMissingBean
ChatMemoryRepository chatMemoryRepository();
@Bean
@ConditionalOnMissingBean
ChatMemory chatMemory(ChatMemoryRepository chatMemoryRepository);
}Package: org.springframework.ai.model.chat.memory.autoconfigure
Bean Methods:
chatMemoryRepository(): Creates an InMemoryChatMemoryRepository bean if no custom repository is definedchatMemory(ChatMemoryRepository): Creates a MessageWindowChatMemory bean with default settings (max 20 messages)Conditions:
ChatMemory and ChatMemoryRepository classes are on the classpath@ConditionalOnMissingBean to allow custom bean definitions to override defaultstessl i tessl/maven-org-springframework-ai--spring-ai-autoconfigure-model-chat-memory@1.1.0