diff --git a/chat-agent-framework/src/main/java/com/sai/chat/agent/framework/distributedid/SnowflakeIdInitializer.java b/chat-agent-framework/src/main/java/com/sai/chat/agent/framework/distributedid/SnowflakeIdInitializer.java index d56278b..89d42ea 100644 --- a/chat-agent-framework/src/main/java/com/sai/chat/agent/framework/distributedid/SnowflakeIdInitializer.java +++ b/chat-agent-framework/src/main/java/com/sai/chat/agent/framework/distributedid/SnowflakeIdInitializer.java @@ -53,14 +53,14 @@ public void init() { try { // 执行 Lua 脚本获取 workerId 和 datacenterId - List result = stringRedisTemplate.execute(script, Collections.emptyList()); + List strResult = stringRedisTemplate.execute(script, Collections.emptyList()); - if (CollUtil.isEmpty(result) || result.size() != 2) { + if (CollUtil.isEmpty(strResult) || strResult.size() != 2) { throw new RuntimeException("从Redis获取WorkerId和DataCenterId失败"); } - Long workerId = result.get(0); - Long datacenterId = result.get(1); + Long workerId = Long.parseLong(strResult.get(0)); + Long datacenterId = Long.parseLong(strResult.get(1)); // 注册到 Hutool 的 IdUtil Snowflake snowflake = new Snowflake(workerId, datacenterId); diff --git a/chat-agent-framework/src/main/resources/lua/snowflake_init.lua b/chat-agent-framework/src/main/resources/lua/snowflake_init.lua index 33da02d..eb9deef 100644 --- a/chat-agent-framework/src/main/resources/lua/snowflake_init.lua +++ b/chat-agent-framework/src/main/resources/lua/snowflake_init.lua @@ -19,6 +19,8 @@ local datacenterId = redis.call('GET', datacenter_key) if not datacenterId then datacenterId = math.floor(math.random() * 32) -- 随机选择 0-31 redis.call('SET', datacenter_key, datacenterId) +else + datacenterId = tonumber(datacenterId) end return {workerId, datacenterId} diff --git a/chat-agent-infra/pom.xml b/chat-agent-infra/pom.xml index d3d51d0..7911a6e 100644 --- a/chat-agent-infra/pom.xml +++ b/chat-agent-infra/pom.xml @@ -26,12 +26,30 @@ okhttp + + + com.pgvector + pgvector + + + + + com.zaxxer + HikariCP + + io.milvus milvus-sdk-java + + + org.postgresql + postgresql + + org.projectlombok diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusConfig.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusConfig.java index 9731bf2..e1e125f 100644 --- a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusConfig.java +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusConfig.java @@ -20,6 +20,7 @@ import io.milvus.v2.client.ConnectConfig; import io.milvus.v2.client.MilvusClientV2; import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -28,9 +29,12 @@ *

* 通过 Spring 容器统一创建并管理 {@link MilvusClientV2} 实例,用于向量数据的增删改查、索引管理等操作 * 支持通过配置文件设置连接地址与可选的访问令牌 + *

+ * 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true} */ @Configuration @RequiredArgsConstructor +@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false) public class MilvusConfig { private final MilvusProperties milvusProperties; diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusProperties.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusProperties.java index 8d35fb0..c35b00a 100644 --- a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusProperties.java +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusProperties.java @@ -20,16 +20,20 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import java.util.ArrayList; import java.util.List; /** * Milvus 向量数据库配置属性 + *

+ * 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true} */ @Data @Configuration @ConfigurationProperties(prefix = "milvus") +@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false) public class MilvusProperties { /** diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreAdmin.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreAdmin.java index 5834bf1..1f1ab41 100644 --- a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreAdmin.java +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreAdmin.java @@ -28,6 +28,7 @@ import io.milvus.v2.service.collection.response.ListCollectionsResp; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -37,10 +38,13 @@ * Milvus 向量空间管理实现 *

* 实现 {@link VectorStoreAdmin} 接口,负责 Collection 的 DDL 操作 + *

+ * 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true} */ @Slf4j @Service @RequiredArgsConstructor +@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false) public class MilvusVectorStoreAdmin implements VectorStoreAdmin { private final MilvusClientV2 milvusClient; diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreService.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreService.java index 5bbeb30..d8fa847 100644 --- a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreService.java +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/MilvusVectorStoreService.java @@ -35,6 +35,7 @@ import io.milvus.v2.service.vector.response.SearchResp; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -45,10 +46,13 @@ * Milvus 向量存储服务实现 *

* 实现 {@link VectorStoreService} 接口,封装 Milvus SDK v2 的增删改查操作 + *

+ * 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true} */ @Slf4j @Service @RequiredArgsConstructor +@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false) public class MilvusVectorStoreService implements VectorStoreService { private final MilvusClientV2 milvusClient; diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorConfig.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorConfig.java new file mode 100644 index 0000000..c809561 --- /dev/null +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorConfig.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 com.sai.chat.agent.infra.vector; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import javax.sql.DataSource; + +/** + * PgVector 向量数据库客户端配置 + *

+ * 通过 Spring 容器统一创建并管理 {@link DataSource} 实例,用于向量数据的增删改查、索引管理等操作。 + * 支持通过配置文件设置连接地址与访问凭证。 + *

+ * 初始化时自动: + * - 启用 pgvector 扩展 + * - 创建默认向量存储表(如不存在) + */ +@Slf4j +@Configuration +@RequiredArgsConstructor +public class PgVectorConfig { + + private final PgVectorProperties pgVectorProperties; + + @Bean + public DataSource pgVectorDataSource() { + PgVectorProperties.TableConfig tableConfig = pgVectorProperties.getTable(); + HikariConfig hikariConfig = new HikariConfig(); + hikariConfig.setJdbcUrl(pgVectorProperties.getJdbcUrl()); + hikariConfig.setUsername(pgVectorProperties.getUsername()); + hikariConfig.setPassword(pgVectorProperties.getPassword()); + hikariConfig.setPoolName("PgVectorHikariPool"); + hikariConfig.setMaximumPoolSize(10); + hikariConfig.setMinimumIdle(2); + hikariConfig.setConnectionTimeout(5000); + hikariConfig.setIdleTimeout(600000); + hikariConfig.setMaxLifetime(1800000); + hikariConfig.setConnectionTestQuery("SELECT 1"); + log.info("PgVector 数据源配置完成, jdbcUrl={}", pgVectorProperties.getJdbcUrl()); + return new HikariDataSource(hikariConfig); + } + + @Bean + public JdbcTemplate pgVectorJdbcTemplate(DataSource pgVectorDataSource) { + return new JdbcTemplate(pgVectorDataSource); + } + + @Bean + public PgVectorInitializer pgVectorInitializer(DataSource pgVectorDataSource, + PgVectorProperties pgVectorProperties) { + return new PgVectorInitializer(pgVectorDataSource, pgVectorProperties); + } +} diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorInitializer.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorInitializer.java new file mode 100644 index 0000000..ff60d49 --- /dev/null +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorInitializer.java @@ -0,0 +1,153 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 com.sai.chat.agent.infra.vector; + +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * PgVector 初始化器 + *

+ * 在 Spring 容器初始化时执行以下一次性操作: + * 1. 启用 pgvector 扩展(CREATE EXTENSION IF NOT EXISTS vector) + * 2. 创建默认向量存储表(如不存在) + */ +@Slf4j +@RequiredArgsConstructor +public class PgVectorInitializer { + + private final DataSource dataSource; + private final PgVectorProperties pgVectorProperties; + + @PostConstruct + public void init() { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + PgVectorProperties.TableConfig tableConfig = pgVectorProperties.getTable(); + String tableName = tableConfig.getDefaultName(); + + enableExtension(jdbcTemplate); + createTableIfAbsent(jdbcTemplate, tableName, tableConfig.getDimension()); + log.info("PgVector 初始化完成, table={}, dimension={}", tableName, tableConfig.getDimension()); + } + + private void enableExtension(JdbcTemplate jdbcTemplate) { + try { + jdbcTemplate.execute("CREATE EXTENSION IF NOT EXISTS vector"); + log.debug("pgvector 扩展启用成功"); + } catch (Exception e) { + log.warn("pgvector 扩展启用失败,请确认 PostgreSQL 已安装 pgvector 插件: {}", e.getMessage()); + } + } + + private void createTableIfAbsent(JdbcTemplate jdbcTemplate, String tableName, int dimension) { + if (tableExists(jdbcTemplate, tableName)) { + log.debug("表已存在,跳过创建: {}", tableName); + return; + } + + String sql = """ + CREATE TABLE IF NOT EXISTS %s ( + id BIGSERIAL PRIMARY KEY, + doc_id VARCHAR(64) NOT NULL, + content TEXT, + embedding VECTOR(%d), + metadata JSONB, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """.formatted(tableName, dimension); + + jdbcTemplate.execute(sql); + log.info("PgVector 表创建成功, table={}, dimension={}", tableName, dimension); + + String indexType = pgVectorProperties.getTable().getIndexType(); + createIndexIfAbsent(jdbcTemplate, tableName, dimension, indexType); + } + + private void createIndexIfAbsent(JdbcTemplate jdbcTemplate, String tableName, + int dimension, String indexType) { + String indexName = tableName + "_embedding_idx"; + if (indexExists(jdbcTemplate, indexName)) { + log.debug("索引已存在,跳过创建: {}", indexName); + return; + } + + String metricType = pgVectorProperties.getTable().getMetricType(); + String vectorField = "embedding"; + + String indexSql = switch (indexType.toLowerCase()) { + case "ivfflat" -> String.format( + "CREATE INDEX IF NOT EXISTS %s ON %s USING ivfflat (%s %s) WITH (lists = 100)", + indexName, tableName, vectorField, metricType); + case "hnsw" -> { + int m = pgVectorProperties.getTable().getM(); + int efConstruction = pgVectorProperties.getTable().getEfConstruction(); + yield String.format( + "CREATE INDEX IF NOT EXISTS %s ON %s USING hnsw (%s %s) WITH (m = %d, ef_construction = %d)", + indexName, tableName, vectorField, metricType, m, efConstruction); + } + default -> { + log.debug("索引类型为 none,跳过索引创建"); + yield null; + } + }; + + if (indexSql != null) { + jdbcTemplate.execute(indexSql); + log.info("PgVector 索引创建成功, index={}, type={}", indexName, indexType); + } + } + + private boolean tableExists(JdbcTemplate jdbcTemplate, String tableName) { + try (Connection conn = dataSource.getConnection()) { + DatabaseMetaData metaData = conn.getMetaData(); + String schema = conn.getSchema(); + try (ResultSet rs = metaData.getTables(null, schema, tableName, new String[]{"TABLE"})) { + return rs.next(); + } + } catch (SQLException e) { + log.warn("检查表是否存在时出错: {}", e.getMessage()); + return false; + } + } + + private boolean indexExists(JdbcTemplate jdbcTemplate, String indexName) { + try (Connection conn = dataSource.getConnection()) { + DatabaseMetaData metaData = conn.getMetaData(); + String schema = conn.getSchema(); + try (ResultSet rs = metaData.getIndexInfo(null, schema, null, true, false)) { + while (rs.next()) { + if (indexName.equals(rs.getString("INDEX_NAME"))) { + return true; + } + } + } + } catch (SQLException e) { + log.warn("检查索引是否存在时出错: {}", e.getMessage()); + } + return false; + } +} diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorProperties.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorProperties.java new file mode 100644 index 0000000..5d2d4c4 --- /dev/null +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorProperties.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 com.sai.chat.agent.infra.vector; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +/** + * PgVector 向量数据库配置属性 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "pgvector") +public class PgVectorProperties { + + /** + * pgvector JDBC 连接地址,例如 jdbc:postgresql://localhost:5432/sai_chat + */ + private String jdbcUrl; + + /** + * 数据库用户名 + */ + private String username; + + /** + * 数据库密码 + */ + private String password; + + /** + * 默认表配置 + */ + private TableConfig table = new TableConfig(); + + /** + * 多租户表映射 + */ + private List tenants = new ArrayList<>(); + + @Data + public static class TableConfig { + /** + * 默认表名 + */ + private String defaultName = "rag_vector_store"; + + /** + * 默认向量维度 + */ + private int dimension = 4096; + + /** + * 距离度量类型:cosine_dist、ip、l2 + */ + private String metricType = "cosine_dist"; + + /** + * 索引类型:none、ivfflat、hnsw + */ + private String indexType = "hnsw"; + + /** + * HNSW 构建参数 - 连接数(默认 16) + */ + private int m = 16; + + /** + * HNSW 构建参数 - 搜索邻居数(默认 64) + */ + private int efConstruction = 64; + + /** + * HNSW 搜索参数 ef(默认 64) + */ + private int efSearch = 64; + } + + @Data + public static class TenantTable { + /** + * 知识库 ID / 租户 ID + */ + private String tenantId; + + /** + * 表名 + */ + private String tableName; + + /** + * 向量维度(可覆盖默认值) + */ + private Integer dimension; + + /** + * 距离度量类型(可覆盖默认值) + */ + private String metricType; + + /** + * 是否启用 + */ + private boolean enabled = true; + } +} diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorStoreAdmin.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorStoreAdmin.java new file mode 100644 index 0000000..d6fbc95 --- /dev/null +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorStoreAdmin.java @@ -0,0 +1,212 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 com.sai.chat.agent.infra.vector; + +import com.sai.chat.agent.framework.errorcode.BaseErrorCode; +import com.sai.chat.agent.framework.exception.ServiceException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * PgVector 向量空间管理实现 + *

+ * 实现 {@link VectorStoreAdmin} 接口,负责表的 DDL 操作。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class PgVectorStoreAdmin implements VectorStoreAdmin { + + private final DataSource pgVectorDataSource; + private final PgVectorProperties pgVectorProperties; + + @Override + public void createCollectionIfAbsent(String collection, int dimension, String metricType) { + if (collectionExists(collection)) { + log.debug("表已存在,跳过创建: {}", collection); + return; + } + + String sql = """ + CREATE TABLE IF NOT EXISTS %s ( + id BIGSERIAL PRIMARY KEY, + doc_id VARCHAR(64) NOT NULL, + content TEXT, + embedding VECTOR(%d), + metadata JSONB, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + """.formatted(collection, dimension); + + try { + JdbcTemplate jdbcTemplate = new JdbcTemplate(pgVectorDataSource); + jdbcTemplate.execute(sql); + log.info("PgVector 表创建成功, table={}, dimension={}, metricType={}", + collection, dimension, metricType); + + buildIndex(jdbcTemplate, collection, dimension, metricType, + pgVectorProperties.getTable().getIndexType()); + } catch (Exception e) { + throw new ServiceException("PgVector 表创建失败: " + collection, e, BaseErrorCode.SERVICE_ERROR); + } + } + + @Override + public void dropCollectionIfPresent(String collection) { + if (!collectionExists(collection)) { + log.debug("表不存在,跳过删除: {}", collection); + return; + } + + try { + JdbcTemplate jdbcTemplate = new JdbcTemplate(pgVectorDataSource); + jdbcTemplate.execute("DROP TABLE IF EXISTS " + collection); + log.info("PgVector 表删除成功, table={}", collection); + } catch (Exception e) { + throw new ServiceException("PgVector 表删除失败: " + collection, e, BaseErrorCode.SERVICE_ERROR); + } + } + + @Override + public boolean collectionExists(String collection) { + try (Connection conn = pgVectorDataSource.getConnection()) { + DatabaseMetaData metaData = conn.getMetaData(); + String schema = conn.getSchema(); + try (ResultSet rs = metaData.getTables(null, schema, collection, new String[]{"TABLE"})) { + return rs.next(); + } + } catch (SQLException e) { + log.warn("检查表是否存在时出错: {}", e.getMessage()); + return false; + } + } + + @Override + public int getCollectionDimension(String collection) { + if (!collectionExists(collection)) { + return -1; + } + + String sql = """ + SELECT embedding::regclass::text + FROM information_schema.columns + WHERE table_schema = current_schema() + AND table_name = '%s' + AND column_name = 'embedding' + """.formatted(collection); + + try { + JdbcTemplate jdbcTemplate = new JdbcTemplate(pgVectorDataSource); + String typeStr = jdbcTemplate.queryForObject(sql, String.class); + if (typeStr == null) { + return -1; + } + if (typeStr.contains("(")) { + String dimStr = typeStr.substring(typeStr.indexOf("(") + 1, typeStr.indexOf(")")); + return Integer.parseInt(dimStr.trim()); + } + } catch (Exception e) { + log.warn("获取表维度失败: {}", e.getMessage()); + } + return pgVectorProperties.getTable().getDimension(); + } + + @Override + public List listCollections() { + String sql = """ + SELECT table_name + FROM information_schema.tables + WHERE table_schema = current_schema() + AND table_type = 'BASE TABLE' + AND EXISTS ( + SELECT 1 FROM information_schema.columns c + WHERE c.table_schema = current_schema() + AND c.table_name = tables.table_name + AND c.column_name = 'embedding' + ) + ORDER BY table_name + """; + + try { + JdbcTemplate jdbcTemplate = new JdbcTemplate(pgVectorDataSource); + return jdbcTemplate.queryForList(sql, String.class); + } catch (Exception e) { + log.warn("列出向量表时出错: {}", e.getMessage()); + return new ArrayList<>(); + } + } + + private void buildIndex(JdbcTemplate jdbcTemplate, String table, int dimension, + String metricType, String indexType) { + String indexName = table + "_embedding_idx"; + if (indexExists(jdbcTemplate, indexName)) { + log.debug("索引已存在,跳过创建: {}", indexName); + return; + } + + String indexSql = switch (indexType.toLowerCase()) { + case "ivfflat" -> String.format( + "CREATE INDEX IF NOT EXISTS %s ON %s USING ivfflat (embedding %s) WITH (lists = 100)", + indexName, table, metricType); + case "hnsw" -> { + int m = pgVectorProperties.getTable().getM(); + int efConstruction = pgVectorProperties.getTable().getEfConstruction(); + yield String.format( + "CREATE INDEX IF NOT EXISTS %s ON %s USING hnsw (embedding %s) WITH (m = %d, ef_construction = %d)", + indexName, table, metricType, m, efConstruction); + } + default -> { + log.debug("索引类型为 none,跳过索引创建"); + yield null; + } + }; + + if (indexSql != null) { + jdbcTemplate.execute(indexSql); + log.info("PgVector 索引创建成功, index={}, type={}", indexName, indexType); + } + } + + private boolean indexExists(JdbcTemplate jdbcTemplate, String indexName) { + try (Connection conn = pgVectorDataSource.getConnection()) { + DatabaseMetaData metaData = conn.getMetaData(); + String schema = conn.getSchema(); + try (ResultSet rs = metaData.getIndexInfo(null, schema, null, true, false)) { + while (rs.next()) { + if (indexName.equals(rs.getString("INDEX_NAME"))) { + return true; + } + } + } + } catch (SQLException e) { + log.warn("检查索引是否存在时出错: {}", e.getMessage()); + } + return false; + } +} diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorStoreService.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorStoreService.java new file mode 100644 index 0000000..41690aa --- /dev/null +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/PgVectorStoreService.java @@ -0,0 +1,258 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 com.sai.chat.agent.infra.vector; + +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.IdUtil; +import com.google.gson.JsonObject; +import com.sai.chat.agent.framework.convention.RetrievedChunk; +import com.sai.chat.agent.framework.exception.ClientException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Service; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * PgVector 向量存储服务实现 + *

+ * 实现 {@link VectorStoreService} 接口,基于 JDBC + pgvector 扩展进行向量增删改查操作。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class PgVectorStoreService implements VectorStoreService { + + private final JdbcTemplate pgVectorJdbcTemplate; + private final PgVectorProperties pgVectorProperties; + + @Override + public void indexDocumentChunks(String tableName, String docId, List chunks) { + Assert.notEmpty(chunks, () -> new ClientException("文档分块不允许为空")); + int dimension = resolveDimension(tableName); + + List batch = new ArrayList<>(); + for (VectorChunk chunk : chunks) { + float[] vector = resolveVector(chunk, dimension); + String chunkPk = chunk.getChunkId() != null ? chunk.getChunkId() : IdUtil.getSnowflakeNextIdStr(); + String content = truncateContent(chunk.getContent()); + JsonObject metadata = buildMetadata(docId, chunk); + String embedding = toPgVectorString(vector); + batch.add(new Object[]{chunkPk, content, embedding, metadata.toString()}); + } + + String sql = """ + INSERT INTO %s (doc_id, content, embedding, metadata) + VALUES (?, ?::vector, ?::jsonb) + """.formatted(tableName); + + int[] results = pgVectorJdbcTemplate.batchUpdate(sql, batch); + int totalInserted = 0; + for (int r : results) { + if (r > 0) { + totalInserted++; + } else if (r == 0) { + totalInserted++; + } + } + log.info("PgVector 写入向量索引成功, table={}, docId={}, rows={}", tableName, docId, totalInserted); + } + + @Override + public void updateChunk(String tableName, String docId, VectorChunk chunk) { + Assert.notNull(chunk, () -> new ClientException("Chunk 对象不能为空")); + int dimension = resolveDimension(tableName); + float[] vector = resolveVector(chunk, dimension); + String chunkPk = chunk.getChunkId() != null ? chunk.getChunkId() : IdUtil.getSnowflakeNextIdStr(); + String content = truncateContent(chunk.getContent()); + JsonObject metadata = buildMetadata(docId, chunk); + String embedding = toPgVectorString(vector); + + String sql = """ + UPDATE %s + SET content = ?, + embedding = ?::vector, + metadata = ?::jsonb, + updated_at = CURRENT_TIMESTAMP + WHERE doc_id = ? + """.formatted(tableName); + + int updated = pgVectorJdbcTemplate.update(sql, content, embedding, metadata.toString(), chunkPk); + if (updated == 0) { + String insertSql = """ + INSERT INTO %s (doc_id, content, embedding, metadata) + VALUES (?, ?::vector, ?::jsonb) + """.formatted(tableName); + pgVectorJdbcTemplate.update(insertSql, chunkPk, content, embedding, metadata.toString()); + log.info("PgVector 更新向量索引(insert)成功, table={}, docId={}, chunkId={}", tableName, docId, chunkPk); + } else { + log.info("PgVector 更新向量索引(update)成功, table={}, docId={}, chunkId={}", tableName, docId, chunkPk); + } + } + + @Override + public void deleteDocumentVectors(String tableName, String docId) { + String sql = "DELETE FROM %s WHERE metadata->>'doc_id' = ?".formatted(tableName); + int deleted = pgVectorJdbcTemplate.update(sql, docId); + log.info("PgVector 删除文档向量成功, table={}, docId={}, deleteCnt={}", tableName, docId, deleted); + } + + @Override + public void deleteChunkById(String tableName, String chunkId) { + String sql = "DELETE FROM %s WHERE doc_id = ?".formatted(tableName); + int deleted = pgVectorJdbcTemplate.update(sql, chunkId); + log.info("PgVector 删除 Chunk 成功, table={}, chunkId={}, deleteCnt={}", tableName, chunkId, deleted); + } + + @Override + public List search(String tableName, float[] queryVector, int topK) { + return doSearch(tableName, queryVector, topK, null); + } + + @Override + public List searchWithFilter(String tableName, float[] queryVector, int topK, String filterExpr) { + return doSearch(tableName, queryVector, topK, filterExpr); + } + + // ================== 内部方法 ================== + + private List doSearch(String tableName, float[] queryVector, int topK, String filterExpr) { + int dimension = resolveDimension(tableName); + if (queryVector.length != dimension) { + throw new ClientException("查询向量维度不匹配,期望 " + dimension + ",实际 " + queryVector.length); + } + + String metricType = resolveMetricType(tableName); + String embedding = toPgVectorString(queryVector); + + String sql; + if (filterExpr != null && !filterExpr.isBlank()) { + sql = """ + SELECT doc_id, content, metadata, + embedding <=> ?::vector AS score + FROM %s + WHERE %s + ORDER BY embedding <=> ?::vector + LIMIT %d + """.formatted(tableName, filterExpr, topK); + return pgVectorJdbcTemplate.query(sql, new RetrievedChunkRowMapper(), embedding, embedding); + } else { + sql = """ + SELECT doc_id, content, metadata, + embedding <=> ?::vector AS score + FROM %s + ORDER BY embedding <=> ?::vector + LIMIT %d + """.formatted(tableName, topK); + return pgVectorJdbcTemplate.query(sql, new RetrievedChunkRowMapper(), embedding); + } + } + + private int resolveDimension(String tableName) { + Integer override = getTenantDimension(tableName); + if (override != null) { + return override; + } + return pgVectorProperties.getTable().getDimension(); + } + + private String resolveMetricType(String tableName) { + if (pgVectorProperties.getTenants() != null) { + return pgVectorProperties.getTenants().stream() + .filter(t -> t.getTableName().equals(tableName) && t.getMetricType() != null) + .findFirst() + .map(PgVectorProperties.TenantTable::getMetricType) + .orElse(pgVectorProperties.getTable().getMetricType()); + } + return pgVectorProperties.getTable().getMetricType(); + } + + private Integer getTenantDimension(String tableName) { + if (pgVectorProperties.getTenants() == null) { + return null; + } + return pgVectorProperties.getTenants().stream() + .filter(t -> t.getTableName().equals(tableName) && t.getDimension() != null) + .findFirst() + .map(PgVectorProperties.TenantTable::getDimension) + .orElse(null); + } + + private JsonObject buildMetadata(String docId, VectorChunk chunk) { + JsonObject metadata = new JsonObject(); + metadata.addProperty("doc_id", docId); + metadata.addProperty("kb_id", chunk.getKbId()); + if (chunk.getIndex() != null) { + metadata.addProperty("chunk_index", chunk.getIndex()); + } + if (chunk.getDocTitle() != null) { + metadata.addProperty("doc_title", chunk.getDocTitle()); + } + if (chunk.getSectionPath() != null) { + metadata.addProperty("section_path", chunk.getSectionPath()); + } + return metadata; + } + + private float[] resolveVector(VectorChunk chunk, int dimension) { + float[] vector = chunk.getEmbedding(); + if (vector == null || vector.length == 0) { + throw new ClientException("向量不能为空"); + } + if (vector.length != dimension) { + throw new ClientException("向量维度不匹配,期望 " + dimension + ",实际 " + vector.length); + } + return vector; + } + + private String truncateContent(String content) { + if (content == null) { + return ""; + } + return content.length() > 65535 ? content.substring(0, 65535) : content; + } + + private String toPgVectorString(float[] v) { + StringBuilder sb = new StringBuilder("["); + for (int i = 0; i < v.length; i++) { + if (i > 0) { + sb.append(","); + } + sb.append(v[i]); + } + sb.append("]"); + return sb.toString(); + } + + private static class RetrievedChunkRowMapper implements RowMapper { + @Override + public RetrievedChunk mapRow(ResultSet rs, int rowNum) throws SQLException { + RetrievedChunk chunk = RetrievedChunk.builder() + .id(rs.getString("doc_id")) + .text(rs.getString("content")) + .score((float) (1.0 - rs.getDouble("score"))) + .build(); + return chunk; + } + } +} diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorChunk.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorChunk.java index deb1699..284229d 100644 --- a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorChunk.java +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorChunk.java @@ -34,7 +34,7 @@ public class VectorChunk { /** - * Chunk 唯一标识(对应 Milvus 主键 doc_id) + * Chunk 唯一标识(对应 pgvector 主键 doc_id) */ private String chunkId; diff --git a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorStoreService.java b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorStoreService.java index 32e53ef..74914f5 100644 --- a/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorStoreService.java +++ b/chat-agent-infra/src/main/java/com/sai/chat/agent/infra/vector/VectorStoreService.java @@ -25,6 +25,8 @@ * 向量存储服务接口 *

* 定义文档向量索引的写入、更新、删除操作 + *

+ * 支持 pgvector(默认)和 Milvus(通过 {@code agent.milvus.enabled=true} 启用) */ public interface VectorStoreService { @@ -78,7 +80,7 @@ public interface VectorStoreService { * @param collection Collection 名称 * @param queryVector 查询向量 * @param topK 返回的最相似结果数量 - * @param filterExpr Milvus 过滤表达式(如 metadata["kb_id"] == "xxx") + * @param filterExpr 过滤表达式(pgvector 格式,如 metadata->>'kb_id' = 'xxx') * @return 检索结果列表 */ List searchWithFilter(String collection, float[] queryVector, int topK, String filterExpr); diff --git a/chat-agent/pom.xml b/chat-agent/pom.xml index 073d2d2..371bedb 100644 --- a/chat-agent/pom.xml +++ b/chat-agent/pom.xml @@ -45,12 +45,6 @@ spring-boot-starter-validation - - - io.milvus - milvus-sdk-java - - org.apache.tika diff --git a/chat-agent/src/main/java/com/sai/chat/agent/rag/core/agent/executor/ReActAgentExecutor.java b/chat-agent/src/main/java/com/sai/chat/agent/rag/core/agent/executor/ReActAgentExecutor.java index cf2cafe..2672c13 100644 --- a/chat-agent/src/main/java/com/sai/chat/agent/rag/core/agent/executor/ReActAgentExecutor.java +++ b/chat-agent/src/main/java/com/sai/chat/agent/rag/core/agent/executor/ReActAgentExecutor.java @@ -40,6 +40,7 @@ import com.sai.chat.agent.rag.core.mcp.RemoteMCPToolExecutor; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import java.util.ArrayList; @@ -67,6 +68,7 @@ */ @Slf4j @Component +@Primary @RequiredArgsConstructor public class ReActAgentExecutor implements AgentExecutor { diff --git a/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/SearchChannel.java b/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/SearchChannel.java index 23b03ea..2d1de20 100644 --- a/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/SearchChannel.java +++ b/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/SearchChannel.java @@ -44,7 +44,7 @@ public interface SearchChannel { /** * 通道是否可用 *

- * 例如:当 Milvus 连接失败时,全局向量通道不可用 + * 例如:当向量数据库连接失败时,向量检索通道不可用 * * @return true 表示通道可用 */ diff --git a/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/VectorGlobalSearchChannel.java b/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/VectorGlobalSearchChannel.java index f746869..3746a53 100644 --- a/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/VectorGlobalSearchChannel.java +++ b/chat-agent/src/main/java/com/sai/chat/agent/rag/core/retrieval/channel/VectorGlobalSearchChannel.java @@ -22,7 +22,7 @@ import com.sai.chat.agent.framework.convention.rag.SearchContext; import com.sai.chat.agent.framework.convention.rag.enums.SearchChannelType; import com.sai.chat.agent.infra.embedding.EmbeddingService; -import com.sai.chat.agent.infra.vector.MilvusProperties; +import com.sai.chat.agent.infra.vector.PgVectorProperties; import com.sai.chat.agent.infra.vector.VectorStoreService; import com.sai.chat.agent.rag.config.RAGProperties; import com.sai.chat.agent.rag.constant.RAGConstant; @@ -52,7 +52,7 @@ public class VectorGlobalSearchChannel implements SearchChannel { private final EmbeddingService embeddingService; private final VectorStoreService vectorStoreService; private final RAGProperties ragProperties; - private final MilvusProperties milvusProperties; + private final PgVectorProperties pgVectorProperties; @Override public SearchChannelResult search(SearchContext ctx, IntentNode node, int topK) { @@ -61,7 +61,7 @@ public SearchChannelResult search(SearchContext ctx, IntentNode node, int topK) try { String question = ctx.getMainQuestion(); int effectiveTopK = computeTopK(topK); - String collection = milvusProperties.getCollection().getDefaultName(); + String collection = pgVectorProperties.getTable().getDefaultName(); // 1. 问题向量化 List embeddingVector = embeddingService.embed(question); diff --git a/chat-agent/src/main/resources-env/dev/application-ai.yml b/chat-agent/src/main/resources-env/dev/application-ai.yml index 414a5d2..867d81b 100644 --- a/chat-agent/src/main/resources-env/dev/application-ai.yml +++ b/chat-agent/src/main/resources-env/dev/application-ai.yml @@ -72,15 +72,16 @@ ai: model: noop priority: 100 -# ================== Milvus 向量数据库配置 ================== -milvus: - uri: ${agent.milvus.uri} - token: ${agent.milvus.token} - collection: - default-name: ${agent.milvus.collection.default-name} - dimension: ${agent.milvus.collection.dimension} - metric-type: ${agent.milvus.collection.metric-type} - index-type: ${agent.milvus.collection.index-type} - vector-field: ${agent.milvus.collection.vector-field} - primary-field: ${agent.milvus.collection.primary-field} - content-field: ${agent.milvus.collection.content-field} +# ================== PgVector 向量数据库配置 ================== +pgvector: + jdbc-url: ${agent.pgvector.jdbc-url} + username: ${agent.pgvector.username} + password: ${agent.pgvector.password} + table: + default-name: ${agent.pgvector.table.default-name} + dimension: ${agent.pgvector.table.dimension} + metric-type: ${agent.pgvector.table.metric-type} + index-type: ${agent.pgvector.table.index-type} + m: ${agent.pgvector.table.m} + ef-construction: ${agent.pgvector.table.ef-construction} + ef-search: ${agent.pgvector.table.ef-search} diff --git a/chat-agent/src/main/resources-env/dev/application-base.yml b/chat-agent/src/main/resources-env/dev/application-base-example.yml similarity index 74% rename from chat-agent/src/main/resources-env/dev/application-base.yml rename to chat-agent/src/main/resources-env/dev/application-base-example.yml index 5794677..92f696b 100644 --- a/chat-agent/src/main/resources-env/dev/application-base.yml +++ b/chat-agent/src/main/resources-env/dev/application-base-example.yml @@ -1,6 +1,5 @@ # ============================================================ # chat-agent 配置入口 -# 修改此文件即可运行,无需其他额外操作 # ============================================================ agent: @@ -10,11 +9,11 @@ agent: # ========== 数据源配置 ========== datasource: - host: 127.0.0.1 + host: localhost port: 3306 username: root password: root - name: sai-chat + name: my_database hikari: connection-timeout: 5000 idle-timeout: 600000 @@ -25,40 +24,41 @@ agent: # ========== Redis 配置 ========== redis: - host: 127.0.0.1 + host: localhost port: 6379 - password: 123456 - database: 4 + password: "" + database: 0 - # ========== Milvus 向量数据库配置 ========== - milvus: - uri: http://localhost:19530 - token: - collection: - default-name: rag_default_store - dimension: 4096 - metric-type: COSINE - index-type: FLAT - vector-field: embedding - primary-field: doc_id - content-field: content + # ========== PgVector 向量数据库配置 ========== + pgvector: + jdbc-url: jdbc:postgresql://localhost:5432/pgvector_db + username: postgres + password: postgres + table: + default-name: rag_vector_store + dimension: 1536 + metric-type: cosine_dist + index-type: hnsw + m: 16 + ef-construction: 64 + ef-search: 64 # ========== AI 模型配置 ========== ai: ollama: url: http://localhost:11434 - chat-model: qwen3:8b-fp16 - embedding-model: qwen3-embedding:8b-fp16 + chat-model: your-chat-model + embedding-model: your-embedding-model bailian: - url: https://dashscope.aliyuncs.com - api-key: - chat-model: qwen3-max - rerank-model: qwen3-rerank + url: https://example.com/api + api-key: your-api-key + chat-model: your-chat-model + rerank-model: your-rerank-model siliconflow: - url: https://api.siliconflow.cn - api-key: - chat-model: Pro/zai-org/GLM-4.7 - embedding-model: Qwen/Qwen3-Embedding-8B + url: https://example.com/api + api-key: your-api-key + chat-model: your-chat-model + embedding-model: your-embedding-model # ========== 应用配置 ========== app: @@ -133,4 +133,4 @@ agent: # ========== 上传配置 ========== upload: max-file-size: 50MB - max-request-size: 100MB + max-request-size: 100MB \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8568b7d..a187f64 100644 --- a/pom.xml +++ b/pom.xml @@ -51,7 +51,7 @@ 1.43.0 2.14.5 4.12.0 - 2.6.6 + 0.1.6 3.2.3 2.40.2 @@ -252,11 +252,11 @@ okhttp ${okhttp.version} - + - io.milvus - milvus-sdk-java - ${milvus-sdk.version} + com.pgvector + pgvector + ${pgvector.version} @@ -272,6 +272,18 @@ s3 ${aws-s3.version} + + + io.milvus + milvus-sdk-java + 2.4.8 + + + + org.postgresql + postgresql + 42.7.3 +