Skip to content

feat(anthropic): add support for prompt caching with fix #4139

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 10 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,71 @@
<?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-jdbc</artifactId>
<packaging>jar</packaging>
<name>Spring AI JDBC Chat Memory Auto Configuration</name>
<description>Spring JDBC AI 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-jdbc</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-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

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

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
<scope>test</scope>
</dependency>

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

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* 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.
*/

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

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.ai.chat.memory.jdbc.JdbcChatMemory;
import org.springframework.ai.chat.memory.jdbc.JdbcChatMemoryConfig;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

/**
* @author Jonathan Leijendekker
* @since 1.0.0
*/
@AutoConfiguration(after = JdbcTemplateAutoConfiguration.class)
@ConditionalOnClass({ JdbcChatMemory.class, DataSource.class, JdbcTemplate.class })
@EnableConfigurationProperties(JdbcChatMemoryProperties.class)
public class JdbcChatMemoryAutoConfiguration {

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

@Bean
@ConditionalOnMissingBean
public JdbcChatMemory chatMemory(JdbcTemplate jdbcTemplate) {
var config = JdbcChatMemoryConfig.builder().jdbcTemplate(jdbcTemplate).build();

return JdbcChatMemory.create(config);
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.ai.chat.memory.jdbc.initialize-schema", havingValue = "true",
matchIfMissing = true)
public DataSourceScriptDatabaseInitializer jdbcChatMemoryScriptDatabaseInitializer(DataSource dataSource) {
logger.debug("Initializing JdbcChatMemory schema");

return new JdbcChatMemoryDataSourceScriptDatabaseInitializer(dataSource);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package org.springframework.ai.model.chat.memory.jdbc.autoconfigure;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer;
import org.springframework.boot.jdbc.init.PlatformPlaceholderDatabaseDriverResolver;
import org.springframework.boot.sql.init.DatabaseInitializationMode;
import org.springframework.boot.sql.init.DatabaseInitializationSettings;

class JdbcChatMemoryDataSourceScriptDatabaseInitializer extends DataSourceScriptDatabaseInitializer {

private static final String SCHEMA_LOCATION = "classpath:org/springframework/ai/chat/memory/jdbc/schema-@@platform@@.sql";

public JdbcChatMemoryDataSourceScriptDatabaseInitializer(DataSource dataSource) {
super(dataSource, getSettings(dataSource));
}

static DatabaseInitializationSettings getSettings(DataSource dataSource) {
var settings = new DatabaseInitializationSettings();
settings.setSchemaLocations(resolveSchemaLocations(dataSource));
settings.setMode(DatabaseInitializationMode.ALWAYS);
settings.setContinueOnError(true);

return settings;
}

static List<String> resolveSchemaLocations(DataSource dataSource) {
var platformResolver = new PlatformPlaceholderDatabaseDriverResolver();

return platformResolver.resolveAll(dataSource, SCHEMA_LOCATION);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* 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.
*/

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

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

/**
* @author Jonathan Leijendekker
* @since 1.0.0
*/
@ConfigurationProperties(JdbcChatMemoryProperties.CONFIG_PREFIX)
public class JdbcChatMemoryProperties {

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

private boolean initializeSchema = true;

public boolean isInitializeSchema() {
return this.initializeSchema;
}

public void setInitializeSchema(boolean initializeSchema) {
this.initializeSchema = initializeSchema;
}

}
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.jdbc.autoconfigure.JdbcChatMemoryAutoConfiguration
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* 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.
*/

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

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

import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

import org.springframework.ai.chat.memory.jdbc.JdbcChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

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

/**
* @author Jonathan Leijendekker
*/
@Testcontainers
class JdbcChatMemoryAutoConfigurationIT {

static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("postgres:17");

@Container
@SuppressWarnings("resource")
static PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>(DEFAULT_IMAGE_NAME)
.withDatabaseName("chat_memory_auto_configuration_test")
.withUsername("postgres")
.withPassword("postgres");

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JdbcChatMemoryAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class))
.withPropertyValues(String.format("spring.datasource.url=%s", postgresContainer.getJdbcUrl()),
String.format("spring.datasource.username=%s", postgresContainer.getUsername()),
String.format("spring.datasource.password=%s", postgresContainer.getPassword()));

@Test
void jdbcChatMemoryScriptDatabaseInitializer_shouldBeLoaded() {
this.contextRunner.withPropertyValues("spring.ai.chat.memory.jdbc.initialize-schema=true").run(context -> {
assertThat(context.containsBean("jdbcChatMemoryScriptDatabaseInitializer")).isTrue();
});
}

@Test
void jdbcChatMemoryScriptDatabaseInitializer_shouldNotBeLoaded() {
this.contextRunner.withPropertyValues("spring.ai.chat.memory.jdbc.initialize-schema=false").run(context -> {
assertThat(context.containsBean("jdbcChatMemoryScriptDatabaseInitializer")).isFalse();
});
}

@Test
void addGetAndClear_shouldAllExecute() {
this.contextRunner.withPropertyValues("spring.ai.chat.memory.jdbc.initialize-schema=true").run(context -> {
var chatMemory = context.getBean(JdbcChatMemory.class);
var conversationId = UUID.randomUUID().toString();
var userMessage = new UserMessage("Message from the user");

chatMemory.add(conversationId, userMessage);

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

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);
});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package org.springframework.ai.model.chat.memory.jdbc.autoconfigure;

import javax.sql.DataSource;

import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;

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

/**
* @author Jonathan Leijendekker
*/
@Testcontainers
class JdbcChatMemoryDataSourceScriptDatabaseInitializerTests {

static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("postgres:17");

@Container
@SuppressWarnings("resource")
static PostgreSQLContainer<?> postgresContainer = new PostgreSQLContainer<>(DEFAULT_IMAGE_NAME)
.withDatabaseName("chat_memory_initializer_test")
.withUsername("postgres")
.withPassword("postgres");

private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JdbcChatMemoryAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class, DataSourceAutoConfiguration.class))
.withPropertyValues(String.format("spring.datasource.url=%s", postgresContainer.getJdbcUrl()),
String.format("spring.datasource.username=%s", postgresContainer.getUsername()),
String.format("spring.datasource.password=%s", postgresContainer.getPassword()));

@Test
void getSettings_shouldHaveSchemaLocations() {
this.contextRunner.run(context -> {
var dataSource = context.getBean(DataSource.class);
var settings = JdbcChatMemoryDataSourceScriptDatabaseInitializer.getSettings(dataSource);

assertThat(settings.getSchemaLocations())
.containsOnly("classpath:org/springframework/ai/chat/memory/jdbc/schema-postgresql.sql");
});
}

}
Loading