AnalyticDB for PostgreSQL长记忆与 Spring AI 集成指南
本指南详细说明了如何将AnalyticDB for PostgreSQL作为持久化长记忆存储,与 Spring AI 框架集成。通过 spring-ai-alibaba 组件,开发者可以为大语言模型应用提供稳定、可检索的对话记忆能力。
前提条件
一个基于 Spring Boot 3.x 的项目工程。
快速入门
引入依赖
在您的项目 pom.xml 文件中,添加以下两个核心依赖。
依赖包请通过钉钉联系阿里云服务支持获取(钉钉账号:1rr-h38w9hwtt5)。
<properties>
<!-- 请将版本号替换为实际获取的版本 -->
<spring-ai-alibaba.version>1.0.0.4</spring-ai-alibaba.version>
</properties>
<dependencies>
<!-- ADBPG 长记忆核心启动器 -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-memory-adbpg</artifactId>
<version>${spring-ai-alibaba.version}</version>
</dependency>
<!-- ADBPG 长记忆自动配置 -->
<dependency>
<groupId>com.alibaba.cloud.ai.autoconfigure.memory.adbpg</groupId>
<artifactId>spring-ai-alibaba-autoconfigure-memory-adbpg</artifactId>
<version>${spring-ai-alibaba.version}</version>
</dependency>
</dependencies>参数配置
在 application.yml 文件中配置必要的连接信息和模型参数。自动配置机制将根据这些参数初始化相关 Beans。
spring:
ai:
# 通义千问的基础配置
dashscope:
api-key: sk-xxxx # 您的API Key
# 阿里云AI套件相关配置
alibaba:
# ADBPG 长记忆专属配置
adbpg:
# 服务端配置:定义长记忆在ADBPG中的存储和处理方式
server: # 注意:此 server 节点必须存在才能触发自动配置
vector-store:
provider: adbpg
config:
port: 3000 # 记忆服务内部端口
dbname: postgres
user: test_user
password: xxxx
# embedding-model-dims 必须与下面 embedder 配置的向量维度一致
embedding-model-dims: 1024
llm:
provider: qwen # 指定用于事实提取等内部处理的LLM
config:
api-key: ${spring.ai.dashscope.api-key} # 引用上方定义的API-Key
base-url: https://dashscope.aliyuncs.com/compatible-mode/v1
model: qwen3-32b # 例如 qwen-plus, qwen-max
embedder:
provider: openai # 指定用于生成向量的Embedding模型
config:
api-key: ${spring.ai.dashscope.api-key}
model: text-embedding-v4 # 例如 text-embedding-v4
openai-base-url: https://dashscope.aliyuncs.com/compatible-mode/v1
embedding-dims: 1024 # 向量维度
# 可选:自定义事实提取的Prompt模板
custom-fact-extraction-prompt: classpath:/prompts/custom_fact_extraction_prompt.st
# 客户端配置:定义应用连接ADBPG数据库的JDBC信息
client:
url: jdbc:postgresql://gp-xxxx-master.gpdb.rds.aliyuncs.com:5432/postgres
username: test_user
password: xxxx
使用示例
初始化
import com.alibaba.cloud.ai.memory.adbpg.advisor.AdbpgChatMemoryAdvisor; import com.alibaba.cloud.ai.memory.adbpg.core.AdbpgServiceClient; import com.alibaba.cloud.ai.memory.adbpg.model.AdbpgServerRequest; public class ADBPGMemoryController { private static final Logger logger = LoggerFactory.getLogger(ADBPGMemoryController.class); private final ChatClient chatClient;//Spring AI 核心接口,用于与大模型进行交互。 private final VectorStore store;//Spring AI 向量存储接口. private final AdbpgServiceClient adbpgServiceClient;//ADB长记忆服务的专用客户端. public ADBPGMemoryController(VectorStore store, AdbpgServiceClient adbpgServiceClient, ChatClient.Builder builder) { this.store = store; this.adbpgServiceClient = adbpgServiceClient; this.chatClient = builder .defaultAdvisors( AdbpgChatMemoryAdvisor.builder(store).build() ) .build(); } public String call(@RequestParam(value = "message", defaultValue = "请给我推荐好玩的游戏") String message, @RequestParam(value = "user_id", defaultValue = "miao") String userId ) { return chatClient.prompt(message) .advisors( a -> a.params(Map.of(USER_ID, userId)) ) .call().content(); } }添加记忆:使用
adbpgServiceClient.addMemory方法添加一条或多条对话记忆。adbpgServiceClient.addMemory( AdbpgServerRequest.MemoryCreate.builder() .userId("test") .messages(List.of( new AdbpgServerRequest.Message("user", "I'm travelling to San Francisco"), new AdbpgServerRequest.Message("assistant", "That's great! I'm going to Dubai next month.")) ) .build()); // 带metadata参数 adbpgServiceClient.addMemory( AdbpgServerRequest.MemoryCreate.builder() .agentId("agent2") .userId("test") .messages(List.of( new AdbpgServerRequest.Message("user", "I'm travelling to San Francisco"), new AdbpgServerRequest.Message("assistant", "That's great! I'm going to Dubai next month.")) ) .metadata(Map.of( "expiration_date", "2026-01-01" )) .build());MemoryCreate结构:字段
类型
是否必选
描述
messagesList<Message>是
对话消息列表,包含角色和内容。
userIdString是
用户唯一标识符。
agentIdString否
Agent唯一标识符,用于隔离不同Agent的记忆。
runIdString否
单次运行的ID,用于追踪。
metadataMap<String, Object>否
自定义元数据,可用于后续的过滤查询。
检索记忆,使用
vectorStore.similaritySearch方法,通过AdbpgServerRequest.SearchRequest构造查询条件。// 按照agent id或者user id来检索 documents = store.similaritySearch(AdbpgServerRequest.SearchRequest.builder().userId("test").agentId("agent2").build()); logger.info("agent的长期记忆: {}", documents); // 按照query和filters来检索 documents = store.similaritySearch( AdbpgServerRequest.SearchRequest.builder() .query("What do you know about me?") .userId("test") .filters(Map.of( "AND", Arrays.asList( Map.of("created_at", Map.of("gte", "2025-07-29", "lte", "2025-11-30")), Map.of("user_id", "test") ) )) .build() );SearchRequest结构:字段
类型
是否必选
描述
queryString否
用于相似度搜索的自然语言查询。
userIdString否
用户唯一标识符,用于限定搜索范围。
agentIdString否
Agent唯一标识符,用于限定搜索范围。
runIdString否
单次运行的ID,用于限定搜索范围。
filtersMap<String, Object>否
基于元数据的结构化过滤条件。
limitsInteger否
返回的最大结果数量。
删除记忆:使用
adbpgServiceClient的deleteMemory或deleteAllMemories方法进行删除记忆。// 按照memory id进行删除 adbpgServiceClient.deleteMemory(documents.stream().findFirst().get().getId()); // 按照user id进行删除 adbpgServiceClient.deleteAllMemories("test", null, null);