全部產品
Search
文件中心

AnalyticDB:基於AnalyticDB PostgreSQL MCP Server實現RAG與長記憶

更新時間:Sep 19, 2025

模型上下文協議(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版執行個體。

說明

您可以在控制台執行個體的基本資料頁查看核心小版本。如不滿足上述版本要求,需要您升級核心小版本

前提條件

  • 如果您需要使用長記憶功能,請提交工單聯絡支援人員協助安裝adbpg_llm_memory外掛程式。

  • 擷取調用大模型服務的API Key。如果您通過阿里雲百鍊平台叫用大模型,擷取方法請參見API Key

操作步驟

本章節以MCP用戶端調用MCP Server功能為例,介紹安裝與調用MCP Server的操作過程。

步驟一:準備專案環境

  1. 建立專案目錄,並進入該目錄。

    mkdir mcp-server-test
    cd mcp-server-test
  2. 使用uv建立並啟用一個Python虛擬環境,以隔離專案依賴與全域環境。

    說明

    uv是較好的Python虛擬環境和依賴管理工具,適合需要運行多個模型的機器。安裝方法請參見Installing uv

    # 建立虛擬環境
    uv venv .venv
    
    # 啟用虛擬環境
    # Linux/macOS:
    source .venv/bin/activate
    # Windows:
    # .venv\Scripts\activate

    啟用成功後,您將看到(.venv)字樣。

步驟二:安裝並配置MCP Server

源碼安裝

  1. 複製倉庫。

    git clone https://github.com/aliyun/alibabacloud-adbpg-mcp-server.git
  2. 安裝依賴軟體包。

    cd alibabacloud-adbpg-mcp-server
    uv pip install -e .
  3. 配置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安裝

  1. 安裝MCP Server。

    uv pip install adbpg_mcp_server
  2. 配置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支援的工具

分類

工具

說明

資料庫操作

execute_select_sql

AnalyticDB PostgreSQL執行個體上執行SELECTSQL查詢語句。

execute_dml_sql

AnalyticDB PostgreSQL執行個體上執行DML(INSERTUPDATEDELETE)SQL語句。

execute_ddl_sql

AnalyticDB PostgreSQL執行個體上執行DDL(CREATEALTERDROP)SQL語句。

analyze_table

收集表資料。

explain_query

獲得查詢的執行計畫。

GraphRAG操作

adbpg_graphrag_upload

上傳檔案給GraphRAG,進行文本切分、向量產生和知識圖譜抽取等操作。

adbpg_graphrag_query

根據查詢模式向GraphRAG提交查詢,返回查詢結果。

LLM長記憶操作

adbpg_llm_memory_add

建立或添加用於大模型的長記憶資訊。

adbpg_llm_memory_get_all

擷取某個UserRunAgent的所有記憶。

adbpg_llm_memory_search

根據給定的query擷取某個UserRunAgent的所有記憶。

adbpg_llm_memory_delete_all

刪除某個UserRunAgent的所有記憶。

資料庫操作

execute_select_sql

  • 描述:在AnalyticDB PostgreSQL執行個體上執行SELECTSQL查詢語句。

  • 參數:SELECTSQL查詢語句。

  • 返回:JSON格式查詢結果。

execute_dml_sql

  • 描述:在AnalyticDB PostgreSQL執行個體上執行DML(INSERTUPDATEDELETE)SQL語句。

  • 參數:DMLSQL語句。

  • 返回:運行結果。

execute_ddl_sql

  • 描述:在AnalyticDB PostgreSQL執行個體上執行DDL(CREATEALTERDROPTRUNCATE)SQL語句。

  • 參數:DDLSQL語句。

  • 返回:運行結果。

analyze_table

  • 描述:收集表資料。

  • 參數:

    • schema (text):schema(模式)。

    • table (text):表名。

  • 返回:explain運行結果。

explain_query

  • 描述:獲得查詢的執行計畫。

  • 參數:explainSQL 陳述式。

  • 返回:運行結果。

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_memoryepisodic_memoryprocedural_memory(一般情況下無需填寫,如果是AI Agent的memory 請填寫 procedural_memory)。

    • prompt (text):相關提示詞或者上下文。

    其中user_idrun_idagent_id至少需要提供一個。

  • 返回:result (json),運行結果,包含idmemoryevent等資訊。

  • 樣本:

    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

  • 描述:擷取某個UserRunAgent的所有記憶。

  • 參數:

    • 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擷取某個UserRunAgent的所有記憶。

  • 參數:

    • 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

  • 描述:刪除某個UserRunAgent的所有記憶。

  • 參數:

    • 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'}