聊聊Spring AI Alibaba的JdbcChatMemory
ztj100 2025-05-03 17:52 15 浏览 0 评论
序
本文主要研究一下Spring AI Alibaba的JdbcChatMemory
JdbcChatMemory
community/memories/spring-ai-alibaba-jdbc-memory/src/main/java/com/alibaba/cloud/ai/memory/jdbc/JdbcChatMemory.java
public abstract class JdbcChatMemory implements ChatMemory, AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(JdbcChatMemory.class);
private static final String DEFAULT_TABLE_NAME = "chat_memory";
private final Connection connection;
private final String tableName;
protected JdbcChatMemory(String username, String password, String jdbcUrl) {
this(username, password, jdbcUrl, DEFAULT_TABLE_NAME);
}
protected JdbcChatMemory(String username, String password, String jdbcUrl, String tableName) {
this.tableName = tableName;
try {
this.connection = DriverManager.getConnection(jdbcUrl, username, password);
checkAndCreateTable();
}
catch (SQLException e) {
throw new RuntimeException("Error connecting to the database", e);
}
}
protected JdbcChatMemory(Connection connection) {
this(connection, DEFAULT_TABLE_NAME);
}
protected JdbcChatMemory(Connection connection, String tableName) {
this.connection = connection;
this.tableName = tableName;
try {
checkAndCreateTable();
}
catch (SQLException e) {
throw new RuntimeException("Error checking the database table", e);
}
}
protected abstract String jdbcType();
protected abstract String hasTableSql(String tableName);
protected abstract String createTableSql(String tableName);
/**
* Generate paginated query SQL based on the database type. Default implementation
* uses LIMIT clause. Subclasses can override this method if their database uses
* different pagination syntax.
* @param tableName The name of the table
* @param lastN Number of records to return, if greater than 0
* @return SQL query string with pagination
*/
protected String generatePaginatedQuerySql(String tableName, int lastN) {
StringBuilder sqlBuilder = new StringBuilder("SELECT messages,type FROM ").append(tableName)
.append(" WHERE conversation_id = ?");
if (lastN > 0) {
sqlBuilder.append(" LIMIT ?");
}
return sqlBuilder.toString();
}
private void checkAndCreateTable() throws SQLException {
String checkTableQuery = hasTableSql(tableName);
try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(checkTableQuery)) {
if (rs.next()) {
logger.info("Table {} exists.", tableName);
}
else {
logger.info("Table {} does not exist. Creating table...", tableName);
createTable();
}
}
}
private void createTable() {
try (Statement stmt = connection.createStatement()) {
stmt.execute(createTableSql(tableName));
logger.info("Table {} created successfully.", tableName);
}
catch (Exception e) {
throw new RuntimeException("Error creating table " + tableName + " ", e);
}
}
@Override
public void add(String conversationId, List<Message> messages) {
try {
for (Message message : messages) {
String sql = "INSERT INTO " + tableName + " (messages, conversation_id, type) VALUES (?, ?, ?)";
try (PreparedStatement stmt = this.connection.prepareStatement(sql)) {
stmt.setString(1, message.getText());
stmt.setString(2, conversationId);
stmt.setString(3, message.getMessageType().name());
stmt.executeUpdate();
}
}
}
catch (Exception e) {
logger.error("Error adding messages to {} chat memory", jdbcType(), e);
throw new RuntimeException(e);
}
}
@Override
public List<Message> get(String conversationId, int lastN) {
return this.selectMessageById(conversationId, lastN);
}
@Override
public void clear(String conversationId) {
String sql = "DELETE FROM " + tableName + " WHERE conversation_id = ?";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, conversationId);
stmt.executeUpdate();
}
catch (Exception e) {
logger.error("Error clearing messages from {} chat memory", jdbcType(), e);
throw new RuntimeException("Error executing delete ", e);
}
}
@Override
public void close() throws Exception {
if (connection != null) {
connection.close();
}
}
public void clearOverLimit(String conversationId, int maxLimit, int deleteSize) {
try {
List<Message> all = this.selectMessageById(conversationId);
if (all.size() >= maxLimit) {
// Delete oldest messages first
String sql = "DELETE FROM " + tableName + " WHERE conversation_id = ? ORDER BY ROWID LIMIT ?";
try (PreparedStatement stmt = this.connection.prepareStatement(sql)) {
stmt.setString(1, conversationId);
stmt.setInt(2, deleteSize);
stmt.executeUpdate();
}
catch (SQLException e) {
// If the database doesn't support ORDER BY in DELETE, fallback to
// alternative approach
all = all.stream().skip(Math.max(0, deleteSize)).toList();
// Clear all messages and reinsert the remaining ones
clear(conversationId);
for (Message message : all) {
add(conversationId, List.of(message));
}
}
}
}
catch (Exception e) {
logger.error("Error clearing messages from {} chat memory", jdbcType(), e);
throw new RuntimeException(e);
}
}
public List<Message> selectMessageById(String conversationId, int lastN) {
List<Message> totalMessage = new ArrayList<>();
String sql = generatePaginatedQuerySql(tableName, lastN);
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
// Set conversation ID parameters.
stmt.setString(1, conversationId);
// If there is a limit, set the limit parameter.
if (lastN > 0) {
stmt.setInt(2, lastN);
}
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
var content = resultSet.getString("messages");
var type = MessageType.valueOf(resultSet.getString("type"));
var message = switch (type) {
case USER -> new UserMessage(content);
case ASSISTANT -> new AssistantMessage(content);
case SYSTEM -> new SystemMessage(content);
default -> null;
};
totalMessage.add(message);
}
}
catch (SQLException e) {
logger.error("select message by {} error,sql:{}", jdbcType(), sql, e);
throw new RuntimeException(e);
}
return totalMessage;
}
public List<Message> selectMessageById(String conversationId) {
return this.selectMessageById(conversationId, 0);
}
}
JdbcChatMemory构造器要求输入String username, String password, String jdbcUrl, String tableName,默认表名为chat_memory,它定义了jdbcType、hasTableSql、createTableSql三个抽象方法;其add方法遍历messages,挨个使用PreparedStatement插入人数据;其get方法则查询指定conversation_id的最近几条记录;其clear方法则删除指定conversation_id的所有记录。
MysqlChatMemory
community/memories/spring-ai-alibaba-jdbc-memory/src/main/java/com/alibaba/cloud/ai/memory/jdbc/MysqlChatMemory.java
public class MysqlChatMemory extends JdbcChatMemory {
private static final String JDBC_TYPE = "mysql";
public MysqlChatMemory(String username, String password, String jdbcUrl) {
super(username, password, jdbcUrl);
}
public MysqlChatMemory(String username, String password, String jdbcUrl, String tableName) {
super(username, password, jdbcUrl, tableName);
}
public MysqlChatMemory(Connection connection) {
super(connection);
}
public MysqlChatMemory(Connection connection, String tableName) {
super(connection, tableName);
}
@Override
protected String jdbcType() {
return JDBC_TYPE;
}
@Override
protected String hasTableSql(String tableName) {
return String.format("SHOW TABLES LIKE '%s'", tableName);
}
@Override
protected String createTableSql(String tableName) {
return String.format(
"CREATE TABLE %s( id BIGINT AUTO_INCREMENT PRIMARY KEY,conversation_id VARCHAR(256) NULL,messages TEXT NULL,type varchar(100) NULL) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;",
tableName);
}
}
MysqlChatMemory继承了JdbcChatMemory,其jdbcType为mysql
OracleChatMemory
community/memories/spring-ai-alibaba-jdbc-memory/src/main/java/com/alibaba/cloud/ai/memory/jdbc/OracleChatMemory.java
public class OracleChatMemory extends JdbcChatMemory {
private static final String JDBC_TYPE = "oracle";
public OracleChatMemory(String username, String password, String url) {
super(username, password, url);
}
public OracleChatMemory(String username, String password, String url, String tableName) {
super(username, password, url, tableName);
}
public OracleChatMemory(Connection connection) {
super(connection);
}
public OracleChatMemory(Connection connection, String tableName) {
super(connection, tableName);
}
@Override
protected String jdbcType() {
return JDBC_TYPE;
}
@Override
protected String hasTableSql(String tableName) {
return String.format("SELECT table_name FROM user_tables WHERE table_name = '%s'", tableName.toUpperCase());
}
@Override
protected String createTableSql(String tableName) {
return String.format(
"CREATE TABLE %s ( id NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, conversation_id VARCHAR2(256), messages CLOB, type VARCHAR2(100));",
tableName);
}
@Override
protected String generatePaginatedQuerySql(String tableName, int lastN) {
StringBuilder sqlBuilder = new StringBuilder().append("SELECT * FROM (")
.append("SELECT messages,type FROM ")
.append(tableName)
.append(" WHERE conversation_id = ?");
if (lastN > 0) {
sqlBuilder.append(" AND ROWNUM <= ?");
}
sqlBuilder.append(")");
return sqlBuilder.toString();
}
}
OracleChatMemory继承了JdbcChatMemory,其jdbcType为oracle,它还额外覆盖了generatePaginatedQuerySql方法
PostgresChatMemory
public class PostgresChatMemory extends JdbcChatMemory {
private static final String JDBC_TYPE = "postgresql";
public PostgresChatMemory(String username, String password, String url) {
super(username, password, url);
}
public PostgresChatMemory(String username, String password, String jdbcUrl, String tableName) {
super(username, password, jdbcUrl, tableName);
}
public PostgresChatMemory(Connection connection) {
super(connection);
}
public PostgresChatMemory(Connection connection, String tableName) {
super(connection, tableName);
}
@Override
protected String jdbcType() {
return JDBC_TYPE;
}
@Override
protected String hasTableSql(String tableName) {
return String.format(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name LIKE '%s'",
tableName);
}
@Override
protected String createTableSql(String tableName) {
return String.format(
"CREATE TABLE %s ( id BIGSERIAL PRIMARY KEY, conversation_id VARCHAR(256), messages TEXT, type VARCHAR(100));",
tableName);
}
}
PostgresChatMemory继承了JdbcChatMemory,其jdbcType为postgresql
SQLiteChatMemory
community/memories/spring-ai-alibaba-jdbc-memory/src/main/java/com/alibaba/cloud/ai/memory/jdbc/SQLiteChatMemory.java
public class SQLiteChatMemory extends JdbcChatMemory {
private static final String JDBC_TYPE = "sqlite";
public SQLiteChatMemory(String username, String password, String jdbcUrl) {
super(username, password, jdbcUrl);
}
public SQLiteChatMemory(String username, String password, String jdbcUrl, String tableName) {
super(username, password, jdbcUrl, tableName);
}
public SQLiteChatMemory(Connection connection) {
super(connection);
}
public SQLiteChatMemory(Connection connection, String tableName) {
super(connection, tableName);
}
@Override
protected String jdbcType() {
return JDBC_TYPE;
}
@Override
protected String hasTableSql(String tableName) {
return String.format("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%s'", tableName);
}
@Override
protected String createTableSql(String tableName) {
return String.format(
"CREATE TABLE IF NOT EXISTS %s ( id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT, messages TEXT, type TEXT);",
tableName);
}
}
SQLiteChatMemory继承了JdbcChatMemory,其jdbcType为sqlite
SqlServerChatMemory
community/memories/spring-ai-alibaba-jdbc-memory/src/main/java/com/alibaba/cloud/ai/memory/jdbc/SqlServerChatMemory.java
public class SqlServerChatMemory extends JdbcChatMemory {
private static final String JDBC_TYPE = "sqlserver";
public SqlServerChatMemory(String username, String password, String url) {
super(username, password, url);
}
public SqlServerChatMemory(String username, String password, String jdbcUrl, String tableName) {
super(username, password, jdbcUrl, tableName);
}
public SqlServerChatMemory(Connection connection) {
super(connection);
}
public SqlServerChatMemory(Connection connection, String tableName) {
super(connection, tableName);
}
@Override
protected String jdbcType() {
return JDBC_TYPE;
}
@Override
protected String hasTableSql(String tableName) {
return String.format("SELECT name FROM sys.tables WHERE name LIKE '%s';", tableName);
}
@Override
protected String createTableSql(String tableName) {
return String.format(
"CREATE TABLE %s (id BIGINT IDENTITY(1,1) PRIMARY KEY, conversation_id NVARCHAR(256), messages NVARCHAR(MAX), type VARCHAR(100));",
tableName);
}
@Override
protected String generatePaginatedQuerySql(String tableName, int lastN) {
StringBuilder sqlBuilder = new StringBuilder("SELECT ");
if (lastN > 0) {
sqlBuilder.append("TOP ").append(lastN).append(" ");
}
sqlBuilder.append("messages,type FROM ").append(tableName).append(" WHERE conversation_id = ?");
return sqlBuilder.toString();
}
}
SqlServerChatMemory继承了JdbcChatMemory,其jdbcType为sqlserver,它还额外覆盖了generatePaginatedQuerySql方法
示例
community/memories/spring-ai-alibaba-jdbc-memory/src/test/java/com/alibaba/cloud/ai/memory/jdbc/MysqlChatMemoryTest.java
class MysqlChatMemoryTest {
@Test
public void test() {
MysqlChatMemory mock = mock(MysqlChatMemory.class);
Assertions.assertNotNull(mock);
}
// @Test
public void mysql() {
MysqlChatMemory chatMemory = new MysqlChatMemory("root", "123456",
"jdbc:mysql://127.0.0.1:3306/spring_ai_alibaba_chat_memory");
String apiKey = System.getenv().getOrDefault("AI_DASHSCOPE_API_KEY", "test-api-key");
ChatClient chatClient = ChatClient.create(new DashScopeChatModel(new DashScopeApi(apiKey)));
String content1 = chatClient.prompt()
.advisors(new MessageChatMemoryAdvisor(chatMemory))
.system("你是一个AI聊天小助手,给人提供情绪价值。")
.user("我是张三")
.call()
.content();
System.out.println(content1);
String content2 = chatClient.prompt()
.advisors(new MessageChatMemoryAdvisor(chatMemory))
.user("我是谁")
.call()
.content();
System.out.println(content2);
Assertions.assertTrue(content2.contains("张三"));
}
小结
spring-ai-alibaba-jdbc-memory提供了ChatMemory的jdbc实现,具体有MysqlChatMemory、OracleChatMemory、PostgresChatMemory、SQLiteChatMemory、SqlServerChatMemory这几种。
doc
- java2ai
相关推荐
- 其实TensorFlow真的很水无非就这30篇熬夜练
-
好的!以下是TensorFlow需要掌握的核心内容,用列表形式呈现,简洁清晰(含表情符号,<300字):1.基础概念与环境TensorFlow架构(计算图、会话->EagerE...
- 交叉验证和超参数调整:如何优化你的机器学习模型
-
准确预测Fitbit的睡眠得分在本文的前两部分中,我获取了Fitbit的睡眠数据并对其进行预处理,将这些数据分为训练集、验证集和测试集,除此之外,我还训练了三种不同的机器学习模型并比较了它们的性能。在...
- 机器学习交叉验证全指南:原理、类型与实战技巧
-
机器学习模型常常需要大量数据,但它们如何与实时新数据协同工作也同样关键。交叉验证是一种通过将数据集分成若干部分、在部分数据上训练模型、在其余数据上测试模型的方法,用来检验模型的表现。这有助于发现过拟合...
- 深度学习中的类别激活热图可视化
-
作者:ValentinaAlto编译:ronghuaiyang导读使用Keras实现图像分类中的激活热图的可视化,帮助更有针对性...
- 超强,必会的机器学习评估指标
-
大侠幸会,在下全网同名[算法金]0基础转AI上岸,多个算法赛Top[日更万日,让更多人享受智能乐趣]构建机器学习模型的关键步骤是检查其性能,这是通过使用验证指标来完成的。选择正确的验证指...
- 机器学习入门教程-第六课:监督学习与非监督学习
-
1.回顾与引入上节课我们谈到了机器学习的一些实战技巧,比如如何处理数据、选择模型以及调整参数。今天,我们将更深入地探讨机器学习的两大类:监督学习和非监督学习。2.监督学习监督学习就像是有老师的教学...
- Python 模型部署不用愁!容器化实战,5 分钟搞定环境配置
-
你是不是也遇到过这种糟心事:花了好几天训练出的Python模型,在自己电脑上跑得顺顺当当,一放到服务器就各种报错。要么是Python版本不对,要么是依赖库冲突,折腾半天还是用不了。别再喊“我...
- 神经网络与传统统计方法的简单对比
-
传统的统计方法如...
- 自回归滞后模型进行多变量时间序列预测
-
下图显示了关于不同类型葡萄酒销量的月度多元时间序列。每种葡萄酒类型都是时间序列中的一个变量。假设要预测其中一个变量。比如,sparklingwine。如何建立一个模型来进行预测呢?一种常见的方...
- 苹果AI策略:慢哲学——科技行业的“长期主义”试金石
-
苹果AI策略的深度原创分析,结合技术伦理、商业逻辑与行业博弈,揭示其“慢哲学”背后的战略智慧:一、反常之举:AI狂潮中的“逆行者”当科技巨头深陷AI军备竞赛,苹果的克制显得格格不入:功能延期:App...
- 时间序列预测全攻略,6大模型代码实操
-
如果你对数据分析感兴趣,希望学习更多的方法论,希望听听经验分享,欢迎移步宝藏公众号...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)