基于AnalyticDB PostgreSQL MCP Server实现RAG与长记忆
模型上下文协议(Model Context Protocol, MCP)为大模型与外部工具之间搭建了高效的信息传递通道。AnalyticDB PostgreSQL MCP Server 是AI Agent与云原生数据仓库AnalyticDB PostgreSQL版之间的通用接口,支持无缝通信,帮助AI Agent检索数据库元数据、执行SQL操作,并提供GraphRAG和大模型长记忆功能。本文介绍如何配置和使用ADB PG MCP Server。
版本限制
内核版本为7.2.1.3及以上的AnalyticDB for PostgreSQL7.0版实例。
前提条件
操作步骤
本章节以MCP客户端调用MCP Server功能为例,介绍安装与调用MCP Server的操作过程。
步骤一:准备项目环境
创建项目目录,并进入该目录。
mkdir mcp-server-test cd mcp-server-test
使用
uv
创建并激活一个Python虚拟环境,以隔离项目依赖与全局环境。说明uv是较好的Python虚拟环境和依赖管理工具,适合需要运行多个模型的机器。安装方法请参见Installing uv。
# 创建虚拟环境 uv venv .venv # 激活虚拟环境 # Linux/macOS: source .venv/bin/activate # Windows: # .venv\Scripts\activate
激活成功后,您将看到
(.venv)
字样。
步骤二:安装并配置MCP Server
源码安装
克隆仓库。
git clone https://github.com/aliyun/alibabacloud-adbpg-mcp-server.git
安装依赖软件包。
cd alibabacloud-adbpg-mcp-server uv pip install -e .
配置MCP Server。在项目目录下新建
config.json
文件,复制以下配置到文件中,并将相关环境变量替换为实际值。"mcpServers": { "adbpg-mcp-server": { "command": "uv", "args": [ "--directory", "/path/to/adbpg-mcp-server", "run", "adbpg-mcp-server" ], "env": { "ADBPG_HOST": "host", "ADBPG_PORT": "port", "ADBPG_USER": "username", "ADBPG_PASSWORD": "password", "ADBPG_DATABASE": "database", "GRAPHRAG_API_KEY": "graphrag llm api key", "GRAPHRAG_BASE_URL": "graphrag llm base url", "GRAPHRAG_LLM_MODEL": "graphrag llm model name", "GRAPHRAG_EMBEDDING_MODEL": "graphrag embedding model name", "GRAPHRAG_EMBEDDING_API_KEY": "graphrag embedding api key", "GRAPHRAG_EMBEDDING_BASE_URL": "graphrag embedding url", "LLMEMORY_API_KEY": "llm memory api_key", "LLMEMORY_BASE_URL": "llm memory base_url", "LLMEMORY_LLM_MODEL": "llm memory model name", "LLMEMORY_EMBEDDING_MODEL": "llm memory embedding model name" } } }
pip安装
安装MCP Server。
uv pip install adbpg_mcp_server
配置MCP Server。在项目目录下新建
config.json
文件,复制以下配置到文件中,并将相关环境变量替换为实际值。"mcpServers": { "adbpg-mcp-server": { "command": "uvx", "args": [ "adbpg-mcp-server" ], "env": { "ADBPG_HOST": "host", "ADBPG_PORT": "port", "ADBPG_USER": "username", "ADBPG_PASSWORD": "password", "ADBPG_DATABASE": "database", "GRAPHRAG_API_KEY": "graphrag api_key", "GRAPHRAG_BASE_URL": "graphrag base_url", "GRAPHRAG_LLM_MODEL": "graphrag model name", "GRAPHRAG_EMBEDDING_MODEL": "graphrag embedding model name", "GRAPHRAG_EMBEDDING_API_KEY": "graphrag embedding api key", "GRAPHRAG_EMBEDDING_BASE_URL": "graphrag embedding url", "LLMEMORY_API_KEY": "llm memory api_key", "LLMEMORY_BASE_URL": "llm memory base_url", "LLMEMORY_LLM_MODEL": "llm memory model name", "LLMEMORY_EMBEDDING_MODEL": "llm memory embedding model name" } } }
参数说明
阿里云百炼的base_url与支持的模型列表,请参见产品简介。
分类 | 环境变量 | 说明 |
数据库连接 | ADBPG_HOST | 数据库主机地址。 |
ADBPG_PORT | 数据库端口。 | |
ADBPG_USER | 数据库用户名。 | |
ADBPG_PASSWORD | 数据库密码。 | |
ADBPG_DATABASE | 数据库名称。 | |
GraphRAG | GRAPHRAG_API_KEY | 提供给GraphRAG的API密钥。 |
GRAPHRAG_BASE_URL | GraphRAG使用的大模型URL。 | |
GRAPHRAG_LLM_MODEL | GraphRAG使用的大模型名。 | |
GRAPHRAG_EMBEDDING_MODEL | GraphRAG使用的嵌入模型名。 | |
GRAPHRAG_EMBEDDING_API_KEY | GraphRAG使用的嵌入模型API密钥。 | |
GRAPHRAG_EMBEDDING_BASE_URL | GraphRAG使用的嵌入模型URL。 | |
GRAPHRAG_ENTITY_TYPES | GraphRAG抽取的实体类型。 | |
GRAPHRAG_RELATIONSHIP_TYPES | GraphRAG抽取的关系类型。 | |
长记忆 | LLMEMORY_API_KEY | 长记忆使用的大模型API密钥。 |
LLMEMORY_BASE_URL | 长记忆使用的大模型URL。 | |
LLMEMORY_LLM_MODEL | 长记忆使用的大模型名。 | |
LLMEMORY_EMBEDDING_MODEL | 长记忆使用的嵌入模型。 |
步骤三:编写并运行客户端脚本
新建main.py
文件,示例代码如下。更多功能请参见MCP Server支持的工具。
import asyncio
import json
from mcp.client.stdio import stdio_client
from mcp import ClientSession, StdioServerParameters
config_file_path = "config.json"
# 读取并解析 JSON 配置文件
try:
with open(config_file_path, "r") as f:
config_data = json.load(f)
# 从解析后的数据中提取我们需要的服务器配置
server_config = config_data["mcpServers"]["adbpg-mcp-server"]
except FileNotFoundError:
print(f"错误:配置文件 '{config_file_path}' 未找到。请确保文件存在于当前目录。")
exit(1)
except (KeyError, TypeError):
print(f"错误:配置文件 '{config_file_path}' 格式不正确。请检查其结构。")
exit(1)
# 为 stdio 连接创建服务器参数
server_params = StdioServerParameters(
# 服务器执行的命令,使用 uv 运行 adbpg_mcp_server.py
command = server_config.get("command"),
# 运行的参数
args = server_config.get("args"),
# 环境变量,默认为 None,表示使用当前环境变量
env = server_config.get("env")
)
async def main():
# 创建 stdio 客户端
async with stdio_client(server_params) as (stdio, write):
# 创建 ClientSession 对象
async with ClientSession(stdio, write) as session:
# 初始化 ClientSession
await session.initialize()
# 列出可用的工具
response = await session.list_tools()
print(response)
print("\n--------------------------------\n")
# 调用工具 execute_select_sql
response = await session.call_tool('execute_select_sql', {'query': 'select 1;'})
print(response)
print("\n--------------------------------\n")
# 调用工具 adbpg_graphrag_query
response = await session.call_tool('adbpg_graphrag_query', {'query_str': 'who are you?', 'query_mode': 'bypass'})
print(response)
print("\n--------------------------------\n")
# 调用工具 adbpg_llm_memory_add
messages = [
{"role": "user", "content": "嗨, 我是张三。 我喜欢徒步,不喜欢剧烈的运动。"},
{"role": "assistant", "content": "你好,张三!徒步是个很棒的爱好,我会记住你的喜好。如果你有任何徒步路线规划、装备推荐或沿途风景的问题,欢迎随时交流。"}
]
response = await session.call_tool('adbpg_llm_memory_add', {
'messages': messages,
'user_id': 'test_u',
})
print(response)
print("\n--------------------------------\n")
# 调用工具 adbpg_llm_memory_get_all
response = await session.call_tool('adbpg_llm_memory_get_all', {'user_id': 'test_u'})
print(response)
print("\n--------------------------------\n")
if __name__ == '__main__':
asyncio.run(main())
返回示例
2025-09-16 20:40:36,995 - mcp.server.lowlevel.server - DEBUG - Initializing server 'adbpg-mcp-server'
2025-09-16 20:40:36,995 - adbpg-mcp-server - INFO - MCP server initialized
2025-09-16 20:40:36,995 - mcp.server.lowlevel.server - DEBUG - Registering handler for ListResourcesRequest
2025-09-16 20:40:36,995 - mcp.server.lowlevel.server - DEBUG - Registering handler for ListResourceTemplatesRequest
2025-09-16 20:40:36,995 - mcp.server.lowlevel.server - DEBUG - Registering handler for ReadResourceRequest
2025-09-16 20:40:36,995 - mcp.server.lowlevel.server - DEBUG - Registering handler for ListToolsRequest
2025-09-16 20:40:36,995 - mcp.server.lowlevel.server - DEBUG - Registering handler for CallToolRequest
2025-09-16 20:40:36,996 - asyncio - DEBUG - Using selector: KqueueSelector
2025-09-16 20:40:36,996 - adbpg_mcp_server.adbpg - INFO - Connecting to database for _conn...
2025-09-16 20:40:37,145 - adbpg_mcp_server.adbpg - INFO - New database connection established and initialized for _conn (id: 4395876432)
2025-09-16 20:40:37,157 - adbpg-mcp-server - INFO - Successfully connected to database.
2025-09-16 20:40:37,157 - adbpg_mcp_server.adbpg - INFO - Connecting to database for _graphrag_conn...
2025-09-16 20:40:37,189 - adbpg_mcp_server.adbpg - INFO - Running initializer for _graphrag_conn on new connection...
2025-09-16 20:40:38,067 - adbpg_mcp_server.adbpg - INFO - New database connection established and initialized for _graphrag_conn (id: 4395131408)
2025-09-16 20:40:38,067 - adbpg-mcp-server - INFO - GraphRAG initialized successfully.
2025-09-16 20:40:38,067 - adbpg_mcp_server.adbpg - INFO - Connecting to database for _llm_memory_conn...
2025-09-16 20:40:38,111 - adbpg_mcp_server.adbpg - INFO - Running initializer for _llm_memory_conn on new connection...
2025-09-16 20:40:39,054 - adbpg_mcp_server.adbpg - INFO - New database connection established and initialized for _llm_memory_conn (id: 4395130768)
2025-09-16 20:40:39,054 - adbpg-mcp-server - INFO - LLM Memory initialized successfully.
2025-09-16 20:40:39,054 - adbpg-mcp-server - INFO - Starting ADBPG MCP server...
2025-09-16 20:40:39,064 - adbpg-mcp-server - INFO - Running MCP server with stdio transport...
2025-09-16 20:40:39,075 - mcp.server.lowlevel.server - DEBUG - Received message: root=InitializedNotification(method='notifications/initialized', params=None, jsonrpc='2.0')
2025-09-16 20:40:39,075 - mcp.server.lowlevel.server - DEBUG - Received message: <mcp.shared.session.RequestResponder object at 0x10607d1d0>
2025-09-16 20:40:39,075 - mcp.server.lowlevel.server - INFO - Processing request of type ListToolsRequest
2025-09-16 20:40:39,075 - mcp.server.lowlevel.server - DEBUG - Dispatching request of type ListToolsRequest
2025-09-16 20:40:39,076 - mcp.server.lowlevel.server - DEBUG - Response sent
meta=None nextCursor=None tools=[Tool(name='execute_select_sql', title=None, description='Execute SELECT SQL to query data from ADBPG database. Returns data in JSON format.', inputSchema={'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The (SELECT) SQL query to execute'}}, 'required': ['query']}, outputSchema=None, annotations=None, meta=None), Tool(name='execute_dml_sql', title=None, description='Execute (INSERT, UPDATE, DELETE) SQL to modify data in ADBPG database.', inputSchema={'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The DML SQL query to execute'}}, 'required': ['query']}, outputSchema=None, annotations=None, meta=None), Tool(name='execute_ddl_sql', title=None, description='Execute (CREATE, ALTER, DROP) SQL statements to manage database objects.', inputSchema={'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The DDL SQL query to execute'}}, 'required': ['query']}, outputSchema=None, annotations=None, meta=None), Tool(name='analyze_table', title=None, description='Execute ANALYZE command to collect table statistics.', inputSchema={'type': 'object', 'properties': {'schema': {'type': 'string'}, 'table': {'type': 'string'}}, 'required': ['schema', 'table']}, outputSchema=None, annotations=None, meta=None), Tool(name='explain_query', title=None, description='Get query execution plan.', inputSchema={'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'The SQL query to analyze'}}, 'required': ['query']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_graphrag_upload', title=None, description='Execute graphrag upload operation', inputSchema={'type': 'object', 'properties': {'filename': {'type': 'string', 'description': 'The file name need to upload'}, 'context': {'type': 'string', 'description': 'the context of your file'}}, 'required': ['filename', 'context']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_graphrag_query', title=None, description='Execute graphrag query operation', inputSchema={'type': 'object', 'properties': {'query_str': {'type': 'string', 'description': 'The query you want to ask'}, 'query_mode': {'type': 'string', 'description': 'The query mode you need to choose [ bypass,naive, local, global, hybrid, mix[default], tree ].'}, 'start_search_node_id': {'type': 'string', 'description': "If using 'tree' query mode, set the start node ID of tree."}}, 'required': ['query_str']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_graphrag_upload_decision_tree', title=None, description=' Upload a decision tree with the specified root_node. If the root_node does not exist, a new decision tree will be created. ', inputSchema={'type': 'object', 'properties': {'root_node': {'type': 'string', 'description': 'the root_noot (optional)'}, 'context': {'type': 'string', 'description': 'the context of decision'}}, 'required': ['context']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_graphrag_append_decision_tree', title=None, description='Append a subtree to an existing decision tree at the node specified by root_node_id. ', inputSchema={'type': 'object', 'properties': {'root_node_id': {'type': 'string', 'description': 'the root_noot_id'}, 'context': {'type': 'string', 'description': 'the context of decision'}}, 'required': ['context', 'root_node_id']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_graphrag_delete_decision_tree', title=None, description=' Delete a sub-decision tree under the node specified by root_node_entity. ', inputSchema={'type': 'object', 'properties': {'root_node_entity': {'type': 'string', 'description': 'the root_noot_entity'}}, 'required': ['root_node_entity']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_graphrag_reset_tree_query', title=None, description=' Reset the decision tree in the tree query mode', inputSchema={'type': 'object', 'required': []}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_llm_memory_add', title=None, description='Execute llm_memory add operation', inputSchema={'type': 'object', 'properties': {'messages': {'type': 'array', 'items': {'type': 'object', 'properties': {'role': {'type': 'string'}, 'content': {'type': 'string'}}, 'required': ['role', 'content']}, 'description': 'List of messages objects (e.g., conversation history)'}, 'user_id': {'type': 'string', 'description': 'the user_id'}, 'run_id': {'type': 'string', 'description': 'the run_id'}, 'agent_id': {'type': 'string', 'description': 'the agent_id'}, 'metadata': {'type': 'object', 'description': 'the metatdata json'}, 'memory_type': {'type': 'string', 'description': 'the memory_type text'}, 'prompt': {'type': 'string', 'description': 'the prompt'}}, 'required': ['messages']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_llm_memory_get_all', title=None, description='Execute llm_memory get_all operation', inputSchema={'type': 'object', 'properties': {'user_id': {'type': 'string', 'description': 'The user_id'}, 'run_id': {'type': 'string', 'description': 'The run_id'}, 'agent_id': {'type': 'string', 'description': 'The agent_id'}}, 'required': []}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_llm_memory_search', title=None, description='Execute llm_memory search operation', inputSchema={'type': 'object', 'properties': {'query': {'type': 'string', 'description': 'llm_memory relevant query'}, 'user_id': {'type': 'string', 'description': 'The search of user_id'}, 'run_id': {'type': 'string', 'description': 'The search of run_id'}, 'agent_id': {'type': 'string', 'description': 'The search of agent_id'}, 'filter': {'type': 'object', 'description': 'The search of filter'}}, 'required': ['query']}, outputSchema=None, annotations=None, meta=None), Tool(name='adbpg_llm_memory_delete_all', title=None, description='Execute llm_memory delete_all operation', inputSchema={'type': 'object', 'properties': {'user_id': {'type': 'string', 'description': 'The user_id'}, 'run_id': {'type': 'string', 'description': 'The run_id'}, 'agent_id': {'type': 'string', 'description': 'The agent_id'}}, 'required': []}, outputSchema=None, annotations=None, meta=None)]
--------------------------------
2025-09-16 20:40:39,079 - mcp.server.lowlevel.server - DEBUG - Received message: <mcp.shared.session.RequestResponder object at 0x10607d310>
2025-09-16 20:40:39,079 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
2025-09-16 20:40:39,079 - mcp.server.lowlevel.server - DEBUG - Dispatching request of type CallToolRequest
2025-09-16 20:40:39,095 - mcp.server.lowlevel.server - DEBUG - Response sent
meta=None content=[TextContent(type='text', text='[\n {\n "?column?": 1\n }\n]', annotations=None, meta=None)] structuredContent=None isError=False
--------------------------------
2025-09-16 20:40:39,096 - mcp.server.lowlevel.server - DEBUG - Received message: <mcp.shared.session.RequestResponder object at 0x105fbd5b0>
2025-09-16 20:40:39,096 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
2025-09-16 20:40:39,096 - mcp.server.lowlevel.server - DEBUG - Dispatching request of type CallToolRequest
2025-09-16 20:40:42,482 - mcp.server.lowlevel.server - DEBUG - Response sent
meta=None content=[TextContent(type='text', text='I am Qwen, a large language model developed by Alibaba Cloud. I have the ability to answer questions, write stories, emails, scripts, and more, as well as perform logical reasoning and programming tasks. I support multiple languages and strive to provide accurate and helpful information. How can I assist you today?', annotations=None, meta=None)] structuredContent=None isError=False
--------------------------------
2025-09-16 20:40:42,486 - mcp.server.lowlevel.server - DEBUG - Received message: <mcp.shared.session.RequestResponder object at 0x105fbcd60>
2025-09-16 20:40:42,487 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
2025-09-16 20:40:42,487 - mcp.server.lowlevel.server - DEBUG - Dispatching request of type CallToolRequest
2025-09-16 20:40:48,351 - mcp.server.lowlevel.server - DEBUG - Response sent
meta=None content=[TextContent(type='text', text="{'results': []}", annotations=None, meta=None)] structuredContent=None isError=False
--------------------------------
2025-09-16 20:40:48,354 - mcp.server.lowlevel.server - DEBUG - Received message: <mcp.shared.session.RequestResponder object at 0x106080830>
2025-09-16 20:40:48,354 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
2025-09-16 20:40:48,354 - mcp.server.lowlevel.server - DEBUG - Dispatching request of type CallToolRequest
2025-09-16 20:40:48,370 - mcp.server.lowlevel.server - DEBUG - Response sent
meta=None content=[TextContent(type='text', text="{'results': [{'id': '72ede2e1-a1ac-435c-8b10-10ffdfb7****', 'memory': '不喜欢剧烈的运动', 'hash': 'b0d6c2f0e5df599e02d8906925cb****', 'metadata': None, 'created_at': '2025-09-15T18:53:22.594877+08:00', 'updated_at': None, 'user_id': 'test_u'}, {'id': 'b041adbb-e191-44e1-84a5-1b83cf85****', 'memory': '名字是张三', 'hash': 'c31d55d5c8a2e6dd7055e46ca861****', 'metadata': None, 'created_at': '2025-09-15T18:53:22.578566+08:00', 'updated_at': None, 'user_id': 'test_u'}, {'id': '99f94dd0-3e7a-471a-8d90-64b670e2****', 'memory': '喜欢徒步', 'hash': 'a6ccce390824f2a7bdcc1a38c400****', 'metadata': None, 'created_at': '2025-09-15T18:53:22.590296+08:00', 'updated_at': None, 'user_id': 'test_u'}]}", annotations=None, meta=None)] structuredContent=None isError=False
--------------------------------
2025-09-16 20:40:48,372 - adbpg_mcp_server.adbpg - INFO - All database connections closed.
MCP Server支持的工具
分类 | 工具 | 说明 |
数据库操作 | 在AnalyticDB PostgreSQL实例上执行 | |
在AnalyticDB PostgreSQL实例上执行DML( | ||
在AnalyticDB PostgreSQL实例上执行DDL( | ||
收集表数据。 | ||
获得查询的执行计划。 | ||
GraphRAG操作 | 上传文件给GraphRAG,进行文本切分、向量生成和知识图谱抽取等操作。 | |
根据查询模式向GraphRAG提交查询,返回查询结果。 | ||
LLM长记忆操作 | 创建或添加用于大模型的长记忆信息。 | |
获取某个 | ||
根据给定的 | ||
删除某个 |
数据库操作
execute_select_sql
描述:在AnalyticDB PostgreSQL实例上执行
SELECT
SQL查询语句。参数:
SELECT
SQL查询语句。返回:JSON格式查询结果。
execute_dml_sql
描述:在AnalyticDB PostgreSQL实例上执行DML(
INSERT
、UPDATE
、DELETE
)SQL语句。参数:
DML
SQL语句。返回:运行结果。
execute_ddl_sql
描述:在AnalyticDB PostgreSQL实例上执行DDL(
CREATE
、ALTER
、DROP
、TRUNCATE
)SQL语句。参数:
DDL
SQL语句。返回:运行结果。
analyze_table
描述:收集表数据。
参数:
schema (text):schema(模式)。
table (text):表名。
返回:
explain
运行结果。
explain_query
描述:获得查询的执行计划。
参数:
explain
SQL 语句。返回:运行结果。
GraphRAG操作
adbpg_graphrag_upload
描述:上传文件给GraphRAG,进行文本切分、向量生成和知识图谱抽取等操作。
参数:
filename (text):文件名称。
context (text):文件内容。
返回:运行结果。
示例:
adbpg_graphrag_upload('产品信息.txt', '小蜜客服系统可以提供问题解答,请假申请,知识库搜索等功能。')
adbpg_graphrag_query
描述:根据查询模式向GraphRAG提交查询,返回查询结果。
参数:
query_str (text):查询的问题。
query_mode (text):查询的模式,默认为mix,可选如下。
bypass:不使用任何向量或知识图谱查询,直接询问大模型。
naive:仅使用向量查询获取相关知识,并提供给大模型参考。
local:仅使用知识图谱中的实体点获取相关知识,并提供给大模型参考。
global:仅使用知识图谱中的关系边获取相关知识,并提供给大模型参考。
hybrid:使用知识图谱的实体点和关系边获取相关知识,并提供给大模型参考。
mix(默认):使用向量匹配与知识图谱来获取相关知识,并提供给大模型参考。
start_search_node_id:如果使用tree查询模式,指定开始的决策树节点id。
返回:response (text),大模型根据 graphRAG 检索到的内容和问题返回的回答响应。
示例:
adbpg_graphrag_query('小蜜有什么功能?', 'hybrid');
LLM长记忆操作
adbpg_llm_memory_add
描述:创建或添加用于大模型的长记忆信息。
参数:
messages (json):需要记忆的信息。
user_id (text):用户id。
run_id (text):运行id。
agent_id (text):智能体id。
metadata (json):额外的元数据,拓展记忆属性。
memory_type (text):记忆类型,支持
semantic_memory
、episodic_memory
和procedural_memory
(一般情况下无需填写,如果是AI Agent的memory 请填写procedural_memory
)。prompt (text):相关提示词或者上下文。
其中
user_id
、run_id
、agent_id
至少需要提供一个。返回:result (json),运行结果,包含
id
、memory
和event
等信息。示例:
adbpg_llm_memory_add($$ [ {"role": "user", "content": "嗨, 我是张三。 我喜欢徒步,不喜欢剧烈的运动,"}, {"role": "assistant", "content": "你好,张三!徒步是个很棒的爱好,我会记住你的喜好。如果你有任何徒步路线规划、装备推荐或沿途风景的问题,欢迎随时交流。"} ] $$, 'test_u', null, null, $${"expiration_date": "2025-08-01"}$$,null,null); -- 返回结果 {'results': [{'id': 'e6d241f9-634f-43e4-925c-0ed70974****', 'memory': 'Name is 张三', 'event': 'ADD'}, {'id': '9efbb099-a20b-483e-99ef-3cc1e85e****', 'memory': 'Likes hiking', 'event': 'ADD'}, {'id': '6fc474d5-1e77-48ec-a5f2-8cb9ec50****', 'mem ory': 'Dislikes intense exercise', 'event': 'ADD'}]}
adbpg_llm_memory_get_all
描述:获取某个
User
、Run
或Agent
的所有记忆。参数:
user_id (text):用户id。
run_id (text):运行id。
agent_id (text):智能体id。
返回:result (json),运行结果。
示例:
adbpg_llm_memory_get_all('test_u', null, null); -- 返回结果 {'results': [{'id': 'e6d241f9-634f-43e4-925c-0ed70974****', 'memory': 'Name is 张三', 'hash': 'd6f327d1ea38b8387927810bdcd3****', 'metadata': {'expiration_date': '2025-08-01'}, 'created_at': '2025-06-10T19:49:03.319454-07:00', 'updated_at': Non e, 'user_id': 'test_u'}, {'id': '9efbb099-a20b-483e-99ef-3cc1e85e****', 'memory': 'Likes hiking', 'hash': '5f8275169192f1a1a4564149c3d1****', 'metadata': {'expiration_date': '2025-08-01'}, 'created_at': '2025-06-10T19:49:03.346516-07:00', 'upda ted_at': None, 'user_id': 'test_u'}, {'id': '6fc474d5-1e77-48ec-a5f2-8cb9ec50****', 'memory': 'Dislikes intense exercise', 'hash': '18fa10d79b6d2b0ec7f271817095****', 'metadata': {'expiration_date': '2025-08-01'}, 'created_at': '2025-06-10T19:4 9:03.372225-07:00', 'updated_at': None, 'user_id': 'test_u'}]}
adbpg_llm_memory_search
描述:根据给定的
query
获取某个User
、Run
或Agent
的所有记忆。参数:
query (text):查询的文本内容。
user_id (text):用户id。
run_id (text):运行id。
agent_id (text):智能体id。
filter (json):额外的过滤条件,json格式(可选)。
返回:result (json),运行结果。
示例:
adbpg_llm_memory_search('给我推荐这周末的运动项目和相关地点?', 'test_33', null, null, null); -- 返回结果 {'results': [{'id': '9efbb099-a20b-483e-99ef-3cc1e85e****', 'memory': 'Likes hiking', 'hash': '5f8275169192f1a1a4564149c3d1****', 'metadata': {'expiration_date': '2025-08-01'}, 'score': 0.7827847450971603, 'created_at': '2025-06-10T19:49:03.346 516-07:00', 'updated_at': None, 'user_id': 'test_33'}, {'id': '6fc474d5-1e77-48ec-a5f2-8cb9ec50****', 'memory': 'Dislikes intense exercise', 'hash': '18fa10d79b6d2b0ec7f271817095****', 'metadata': {'expiration_date': '2025-08-01'}, 'score': 0.82 61472880840302, 'created_at': '2025-06-10T19:49:03.372225-07:00', 'updated_at': None, 'user_id': 'test_33'}, {'id': 'e6d241f9-634f-43e4-925c-0ed70974****', 'memory': 'Name is 张三', 'hash': 'd6f327d1ea38b8387927810bdcd3****', 'metadata': {'expir ation_date': '2025-08-01'}, 'score': 1.0322720631957054, 'created_at': '2025-06-10T19:49:03.319454-07:00', 'updated_at': None, 'user_id': 'test_33'}]}
adbpg_llm_memory_delete_all
描述:删除某个
User
、Run
或Agent
的所有记忆。参数:
user_id (text):用户id。
run_id (text):运行id。
agent_id (text):智能体id。
返回:result (json),运行结果。
示例:
adbpg_llm_memory_delete_all('test_u', null, null); -- 返回结果 {'message': 'All relevant memories deleted'}