All Products
Search
Document Center

AnalyticDB:Implement RAG and long-term memory using the AnalyticDB PostgreSQL MCP Server

Last Updated:Sep 18, 2025

The Model Context Protocol (MCP) provides an efficient communication channel between large language models (LLMs) and external tools. The AnalyticDB PostgreSQL MCP Server is a universal interface between AI agents and the cloud-native data warehouse AnalyticDB for PostgreSQL. It supports seamless communication, allows AI agents to retrieve database metadata and execute SQL operations, and provides retrieval-augmented generation (RAG) and long-term memory for LLMs. This topic describes how to configure and use the AnalyticDB for PostgreSQL MCP Server.

Version requirements

An AnalyticDB for PostgreSQL V7.0 instance with minor engine version 7.2.1.3 or later.

Note

You can view the minor version on the Basic Information page of an instance in the AnalyticDB for PostgreSQL console. If your instance does not meet the required versions, update the minor version of the instance.

Prerequisites

  • To use the long-term memory feature, you must submit a ticket to technical support to request the installation of the adbpg_llm_memory plug-in.

  • Obtain an API key to call the LLM service. If you use Alibaba Cloud Model Studio, see API Key for instructions on obtaining the key.

Procedure

This section provides an example of an MCP client calling the MCP Server to demonstrate how to install and use the server.

Step 1: Prepare the project environment

  1. Create a project folder and navigate to it.

    mkdir mcp-server-test
    cd mcp-server-test
  2. Use uv to create and activate a Python virtual environment. This isolates project dependencies from the global environment.

    Note

    uv is a robust tool for managing Python virtual environments and dependencies, ideal for machines that run multiple models. For installation instructions, see Installing uv.

    # Create the virtual environment
    uv venv .venv
    
    # Activate the virtual environment
    # Linux/macOS:
    source .venv/bin/activate
    # Windows:
    # .venv\Scripts\activate

    After activation, the prompt displays (.venv).

Step 2: Install and configure the MCP Server

Install from source code

  1. Clone the repository.

    git clone https://github.com/aliyun/alibabacloud-adbpg-mcp-server.git
  2. Install the dependency packages.

    cd alibabacloud-adbpg-mcp-server
    uv pip install -e .
  3. Configure the MCP Server. In the project folder, create a config.json file. Copy the following configuration into the file and replace the environment variables with your actual values.

    "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"
        }
      }
    }

Install using pip

  1. Install the MCP Server.

    uv pip install adbpg_mcp_server
  2. Configure the MCP Server. In the project folder, create a config.json file. Copy the following configuration into the file and replace the environment variables with your actual values.

    "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"
        }
      }
    }

Parameter description

Note

For the base_url and a list of supported models for Alibaba Cloud Model Studio, see Product Introduction.

Category

Environment variable

Description

Database connection

ADBPG_HOST

The host address of the database.

ADBPG_PORT

The port of the database.

ADBPG_USER

The username for the database.

ADBPG_PASSWORD

The password for the database.

ADBPG_DATABASE

The name of the database.

GraphRAG

GRAPHRAG_API_KEY

The API key for GraphRAG.

GRAPHRAG_BASE_URL

The URL of the LLM used by GraphRAG.

GRAPHRAG_LLM_MODEL

The name of the LLM used by GraphRAG.

GRAPHRAG_EMBEDDING_MODEL

The name of the embedding model used by GraphRAG.

GRAPHRAG_EMBEDDING_API_KEY

The API key for the embedding model used by GraphRAG.

GRAPHRAG_EMBEDDING_BASE_URL

The URL of the embedding model used by GraphRAG.

GRAPHRAG_ENTITY_TYPES

The entity types extracted by GraphRAG.

GRAPHRAG_RELATIONSHIP_TYPES

The relationship types extracted by GraphRAG.

Long-term memory

LLMEMORY_API_KEY

The API key for the LLM used by long-term memory.

LLMEMORY_BASE_URL

The URL of the LLM used by long-term memory.

LLMEMORY_LLM_MODEL

The name of the LLM used by long-term memory.

LLMEMORY_EMBEDDING_MODEL

The embedding model used by long-term memory.

Step 3: Write and run the client script

Create a main.py file and add the following sample code. For more information about the available features, see Tools supported by the MCP Server.

import asyncio
import json

from mcp.client.stdio import stdio_client
from mcp import ClientSession, StdioServerParameters

config_file_path = "config.json"

# Read and parse the JSON configuration file
try:
    with open(config_file_path, "r") as f:
        config_data = json.load(f)
    # Extract the required server configuration from the parsed data
    server_config = config_data["mcpServers"]["adbpg-mcp-server"]
except FileNotFoundError:
    print(f"Error: Configuration file '{config_file_path}' not found. Make sure the file exists in the current folder.")
    exit(1)
except (KeyError, TypeError):
    print(f"Error: The format of the configuration file '{config_file_path}' is incorrect. Check its structure.")
    exit(1)

# Create server parameters for the stdio connection
server_params = StdioServerParameters(
    # The command to execute on the server, using uv to run adbpg-mcp-server
    command = server_config.get("command"),
    # The arguments to run
    args = server_config.get("args"),
    # Environment variables. The default is None, which means the current environment variables are used.
    env = server_config.get("env")
)

async def main():
    # Create an stdio client
    async with stdio_client(server_params) as (stdio, write):
        # Create a ClientSession object
        async with ClientSession(stdio, write) as session:
            # Initialize the ClientSession
            await session.initialize()

            # List the available tools
            response = await session.list_tools()
            print(response)
            print("\n--------------------------------\n")

            # Call the execute_select_sql tool
            response = await session.call_tool('execute_select_sql', {'query': 'select 1;'})
            print(response)
            print("\n--------------------------------\n")

            # Call the adbpg_graphrag_query tool
            response = await session.call_tool('adbpg_graphrag_query', {'query_str': 'who are you?', 'query_mode': 'bypass'})
            print(response)
            print("\n--------------------------------\n")
            
            # Call the adbpg_llm_memory_add tool
            messages = [
                {"role": "user", "content": "Hi, I'm Zhang San. I like hiking and dislike strenuous exercise."},
                {"role": "assistant", "content": "Hello, Zhang San! Hiking is a great hobby. I will remember your preferences. If you have any questions about planning hiking routes, gear recommendations, or scenic spots, feel free to ask."}
            ]
            response = await session.call_tool('adbpg_llm_memory_add', {
                'messages': messages,
                'user_id': 'test_u',
            })
            print(response)
            print("\n--------------------------------\n")

            # Call the adbpg_llm_memory_get_all tool
            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())

Sample response

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, along with 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': 'Dislikes strenuous exercise', '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': 'Name is Zhang San', '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': 'Likes hiking', '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.

Tools supported by the MCP Server

Category

Tool

Description

Database operations

execute_select_sql

Executes a SELECT SQL query on an AnalyticDB PostgreSQL instance.

execute_dml_sql

Executes DML (INSERT, UPDATE, DELETE) SQL statements on an AnalyticDB PostgreSQL instance.

execute_ddl_sql

Executes DDL (CREATE, ALTER, DROP) SQL statements on an AnalyticDB PostgreSQL instance.

analyze_table

Collects table data.

explain_query

Gets the execution plan for a query.

GraphRAG operations

adbpg_graphrag_upload

Uploads a file to GraphRAG for operations such as text chunking, vector generation, and knowledge graph extraction.

adbpg_graphrag_query

Submits a query to GraphRAG based on the specified query mode and returns the result.

LLM long-term memory operations

adbpg_llm_memory_add

Creates or adds long-term memory information for an LLM.

adbpg_llm_memory_get_all

Gets all memories for a specific User, Run, or Agent.

adbpg_llm_memory_search

Gets all memories for a specific User, Run, or Agent based on the given query.

adbpg_llm_memory_delete_all

Deletes all memories for a specific User, Run, or Agent.

Database operations

execute_select_sql

  • Description: Executes a SELECT SQL query on an AnalyticDB PostgreSQL instance.

  • Parameter: The SELECT SQL query.

  • Returns: The query result in JSON format.

execute_dml_sql

  • Description: Executes DML (INSERT, UPDATE, DELETE) SQL statements on an AnalyticDB PostgreSQL instance.

  • Parameter: The DML SQL statement.

  • Returns: The execution result.

execute_ddl_sql

  • Description: Executes DDL (CREATE, ALTER, DROP, TRUNCATE) SQL statements on an AnalyticDB PostgreSQL instance.

  • Parameter: The DDL SQL statement.

  • Returns: The execution result.

analyze_table

  • Description: Collects statistics about a table.

  • Parameters:

    • schema (text): The schema.

    • table (text): The table name.

  • Returns the result of the explain operation.

explain_query

  • Description: Retrieves the execution plan for a query.

  • Parameter: The explain SQL statement.

  • Returns: The execution result.

GraphRAG operations

adbpg_graphrag_upload

  • Description: Uploads a file to GraphRAG for operations such as text chunking, vector generation, and knowledge graph extraction.

  • Parameters:

    • filename (text): The file name.

    • context (text): The file content.

  • Returns: The execution result.

  • Example:

    adbpg_graphrag_upload('product_info.txt', 'The customer service system can answer questions, process leave requests, and search the knowledge base.')

adbpg_graphrag_query

  • Description: Submits a query to GraphRAG based on the specified query mode and returns the result.

  • Parameters:

    • query_str (text): The question to query.

    • query_mode (text): The query mode. The default value is mix. Valid values include the following:

      • bypass: Directly queries the LLM without using any vector or knowledge graph search.

      • naive: Uses only vector search to retrieve relevant knowledge and provides it to the LLM for reference.

      • local: Uses only entity nodes in the knowledge graph to retrieve relevant knowledge and provides it to the LLM for reference.

      • global: Uses only relationship edges in the knowledge graph to retrieve relevant knowledge and provides it to the LLM for reference.

      • hybrid: Uses both entity nodes and relationship edges in the knowledge graph to retrieve relevant knowledge and provides it to the LLM for reference.

      • mix (default): Uses both vector matching and the knowledge graph to retrieve relevant knowledge and provides it to the LLM for reference.

    • start_search_node_id: If you use the tree query mode, specify the ID of the starting decision tree node.

  • Returns: response (text). The response from the LLM, based on the content retrieved by GraphRAG and the original question.

  • Example:

    adbpg_graphrag_query('What features does the customer service system have?', 'hybrid');

LLM long-term memory operations

adbpg_llm_memory_add

  • Description: Creates or adds long-term memory information for an LLM.

  • Parameters:

    • messages (json): The information to be remembered.

    • user_id (text): The user ID.

    • run_id (text): The run ID.

    • agent_id (text): The agent ID.

    • metadata (json): Additional metadata to extend memory properties.

    • memory_type (text): The memory type. Supported types are semantic_memory, episodic_memory, and procedural_memory. You do not typically need to specify this parameter. However, for an AI agent's memory, set it to procedural_memory.

    • prompt (text): The relevant prompt or context.

    You must provide at least one of user_id, run_id, or agent_id.

  • Returns: result (json). The execution result, which includes information such as id, memory, and event.

  • Example:

    adbpg_llm_memory_add($$
    [
        {"role": "user", "content": "Hi, I'm Zhang San. I like hiking and dislike strenuous exercise,"},
        {"role": "assistant", "content": "Hello, Zhang San! Hiking is a great hobby. I will remember your preferences. If you have any questions about planning hiking routes, gear recommendations, or scenic spots, feel free to ask."}
    ]
    $$, 'test_u', null, null, $${"expiration_date": "2025-08-01"}$$,null,null);
    
    -- Returns
    {'results': [{'id': 'e6d241f9-634f-43e4-925c-0ed70974****', 'memory': 'Name is Zhang San', '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

  • Description: Retrieves all memories for a specific User, Run, or Agent.

  • Parameters:

    • user_id (text): The user ID.

    • run_id (text): The run ID.

    • agent_id (text): The agent ID.

  • Returns: result (json). The execution result.

  • Example:

    adbpg_llm_memory_get_all('test_u', null, null);
    
    -- Returns
    {'results': [{'id': 'e6d241f9-634f-43e4-925c-0ed70974****', 'memory': 'Name is Zhang San', '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

  • Description: Retrieves all memories for a specific User, Run, or Agent based on the specified query.

  • Parameters:

    • query (text): The text content of the query.

    • user_id (text): The user ID.

    • run_id (text): The run ID.

    • agent_id (text): The agent ID.

    • filter (json): Additional filter conditions in JSON format (optional).

  • Returns: result (json). The execution result.

  • Example:

    adbpg_llm_memory_search('Can you recommend some sports and related locations for this weekend?', 'test_33', null, null, null);
    
    -- Returns
     {'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 Zhang San', '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

  • Description: Deletes all memories for a specific User, Run, or Agent.

  • Parameters:

    • user_id (text): The user ID.

    • run_id (text): The run ID.

    • agent_id (text): The agent ID.

  • Returns: result (json). The execution result.

  • Example:

    adbpg_llm_memory_delete_all('test_u', null, null);
    
    -- Returns
    {'message': 'All relevant memories deleted'}