Skip to content

Create MongoDB chat memory implementation #2679

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../../../../pom.xml</relativePath>
</parent>
<artifactId>spring-ai-autoconfigure-model-chat-memory-mongodb</artifactId>
<packaging>jar</packaging>
<name>Spring AI MongoDB Chat Memory Auto Configuration</name>
<description>Spring AI MongoDB Chat Memory Auto Configuration</description>
<url>https://github.com/spring-projects/spring-ai</url>

<scm>
<url>https://github.com/spring-projects/spring-ai</url>
<connection>git://github.com/spring-projects/spring-ai.git</connection>
<developerConnection>[email protected]:spring-projects/spring-ai.git</developerConnection>
</scm>


<dependencies>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-model-chat-memory-mongodb</artifactId>
<version>${project.parent.version}</version>
</dependency>

<!-- Boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>

<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-test</artifactId>
<version>${project.parent.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-client</artifactId>
<version>${project.parent.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai</artifactId>
<version>${project.parent.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mongodb</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright 2025-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.model.chat.memory.mongo.autoconfigure;

import org.springframework.ai.chat.memory.mongo.MongoChatMemory;
import org.springframework.ai.chat.memory.mongo.MongoChatMemoryConfig;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
* Spring Boot auto-configuration for {@link MongoChatMemory}.
*
* @author Łukasz Jernaś
* @since 1.0.0
*/
@AutoConfiguration(after = MongoAutoConfiguration.class)
@EnableConfigurationProperties(MongoChatMemoryProperties.class)
public class MongoChatMemoryAutoConfiguration {

@Bean
@ConditionalOnMissingBean
public MongoChatMemory chatMemory(MongoTemplate mongoTemplate) {
var config = MongoChatMemoryConfig.builder().withTemplate(mongoTemplate).build();
return new MongoChatMemory(config);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright 2025-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.model.chat.memory.mongo.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.memory.mongo.Conversation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.stereotype.Component;

/**
* Class responsible for creating MongoDB proper indices for the ChatMemory. Creates a
* main index on the conversationId and timestamp fields, and a TTL index on the timestamp
* field if the TTL is set in properties.
*
* @author Łukasz Jernaś
* @see MongoChatMemoryProperties
* @since 1.0.0
*/
@Component
@ConditionalOnProperty(value = "spring.ai.chat.memory.mongodb.create-indices", havingValue = "true")
public class MongoChatMemoryIndexCreator {

private static final Logger logger = LoggerFactory.getLogger(MongoChatMemoryIndexCreator.class);

private final MongoTemplate mongoTemplate;

private final MongoChatMemoryProperties mongoChatMemoryProperties;

public MongoChatMemoryIndexCreator(MongoTemplate mongoTemplate,
MongoChatMemoryProperties mongoChatMemoryProperties) {
this.mongoTemplate = mongoTemplate;
this.mongoChatMemoryProperties = mongoChatMemoryProperties;
}

@EventListener(ContextRefreshedEvent.class)
public void initIndicesAfterStartup() {
logger.info("Creating MongoDB indices for ChatMemory");
// Create a main index
mongoTemplate.indexOps(Conversation.class)
.ensureIndex(new Index().on("conversationId", Sort.Direction.ASC).on("timestamp", Sort.Direction.DESC));

createOrUpdateTtlIndex();
}

private void createOrUpdateTtlIndex() {
if (!this.mongoChatMemoryProperties.getTtl().isZero()) {
// Check for existing TTL index
mongoTemplate.indexOps(Conversation.class).getIndexInfo().forEach(idx -> {
if (idx.getExpireAfter().isPresent()
&& !idx.getExpireAfter().get().equals(this.mongoChatMemoryProperties.getTtl())) {
logger.warn("Dropping existing TTL index, because TTL is different");
mongoTemplate.indexOps(Conversation.class).dropIndex(idx.getName());
}
});
mongoTemplate.indexOps(Conversation.class)
.ensureIndex(new Index().on("timestamp", Sort.Direction.ASC)
.expire(this.mongoChatMemoryProperties.getTtl()));
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2025-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.model.chat.memory.mongo.autoconfigure;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.time.Duration;

/**
* @author Łukasz Jernaś
* @since 1.0.0
*/
@ConfigurationProperties(MongoChatMemoryProperties.CONFIG_PREFIX)
public class MongoChatMemoryProperties {

public static final String CONFIG_PREFIX = "spring.ai.chat.memory.mongodb";

/**
* If the indexes should be automatically created on app startup. Note: Changing the
* TTL value will drop the TTL index and recreate it.
*/
private boolean createIndices = false;

/**
* The time to live (TTL) for the conversation documents in the database. The default
* value is 0, which means that the documents will not expire.
*/
private Duration ttl = Duration.ZERO;

public Duration getTtl() {
return ttl;
}

public void setTtl(Duration ttl) {
this.ttl = ttl;
}

public boolean isCreateIndices() {
return createIndices;
}

public void setCreateIndices(boolean createIndices) {
this.createIndices = createIndices;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#
# Copyright 2024-2025 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
org.springframework.ai.model.chat.memory.mongo.autoconfigure.MongoChatMemoryAutoConfiguration
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright 2025-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.ai.model.chat.memory.mongo.autoconfigure;

import org.junit.jupiter.api.Test;
import org.springframework.ai.chat.memory.mongo.MongoChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.util.List;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

@Testcontainers
class MongoChatMemoryAutoConfigurationIT {

@Container
@ServiceConnection
static MongoDBContainer mongoDbContainer = new MongoDBContainer("mongo:8.0.6");

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MongoDbChatMemoryAutoConfiguration.class, MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, MongoChatMemoryIndexCreator.class))
.withPropertyValues(String.format("spring.data.mongodb.uri=%s/ai_test", mongoDbContainer.getConnectionString()),
"spring.ai.chat.memory.mongodb.create-indexes=true", "spring.ai.chat.memory.mongodb.ttl=PT1M");

@Test
void mongodbChatMemoryBean_exists() {
this.contextRunner.run(context -> assertThat(context.containsBean("chatMemory")).isTrue());
}

@Test
void allMethods_shouldExecute() {
this.contextRunner.run(context -> {
var chatMemory = context.getBean(MongoChatMemory.class);
var conversationId = UUID.randomUUID().toString();
var systemMessage = new SystemMessage("Some system message");

chatMemory.add(conversationId, systemMessage);

assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).hasSize(1);
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).isEqualTo(List.of(systemMessage));

chatMemory.clear(conversationId);

assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).isEmpty();

var multipleMessages = List.<Message>of(new UserMessage("Message from the user 1"),
new AssistantMessage("Message from the assistant 1"));

chatMemory.add(conversationId, multipleMessages);

assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).hasSize(multipleMessages.size());
assertThat(chatMemory.get(conversationId, Integer.MAX_VALUE)).isEqualTo(multipleMessages);
});
}

}
Loading