すべてのプロダクト
Search
ドキュメントセンター

AnalyticDB:AnalyticDB PostgreSQL MCP サーバーを使用した RAG と長期記憶の実装

最終更新日:Nov 09, 2025

モデルコンテキストプロトコル (MCP) は、大規模言語モデル (LLM) と外部ツール間の効率的な通信チャネルを提供します。AnalyticDB PostgreSQL MCP サーバーは、AI エージェントとクラウドネイティブデータウェアハウス AnalyticDB for PostgreSQL 間のユニバーサルインターフェイスです。シームレスな通信をサポートし、AI エージェントがデータベースのメタデータを取得して SQL 操作を実行できるようにし、LLM に検索拡張生成 (RAG) と長期記憶を提供します。このトピックでは、AnalyticDB for PostgreSQL MCP サーバーの構成方法と使用方法について説明します。

バージョン要件

AnalyticDB for PostgreSQL V7.0 インスタンスで、マイナーエンジンバージョンが 7.2.1.3 以降であること。

説明

AnalyticDB for PostgreSQL コンソールのインスタンスの[基本情報] ページで、マイナーバージョンを確認できます。 インスタンスが必要なバージョンを満たしていない場合は、インスタンスのマイナーバージョンを更新してください

前提条件

  • 長期記憶機能を使用するには、チケットを送信して、テクニカルサポートに adbpg_llm_memory プラグインのインストールをリクエストする必要があります。

  • LLM サービスを呼び出すための API キーを取得します。Alibaba Cloud Model Studio を使用する場合は、キーの取得手順について「API キー」をご参照ください。

手順

このセクションでは、MCP クライアントが MCP サーバーを呼び出す例を示し、サーバーのインストール方法と使用方法を説明します。

ステップ 1: プロジェクト環境の準備

  1. プロジェクトフォルダを作成し、そこに移動します。

    mkdir mcp-server-test
    cd mcp-server-test
  2. uv を使用して Python 仮想環境を作成し、アクティブ化します。これにより、プロジェクトの依存関係がグローバル環境から分離されます。

    説明

    uv は、Python の仮想環境と依存関係を管理するための堅牢なツールであり、複数のモデルを実行するマシンに最適です。インストール手順については、「uv のインストール」をご参照ください。

    # 仮想環境を作成する
    uv venv .venv
    
    # 仮想環境をアクティブ化する
    # Linux/macOS:
    source .venv/bin/activate
    # Windows:
    # .venv\Scripts\activate

    アクティブ化後、プロンプトに (.venv) が表示されます。

ステップ 2: MCP サーバーのインストールと構成

ソースコードからインストール

  1. リポジトリをクローンします。

    git clone https://github.com/aliyun/alibabacloud-adbpg-mcp-server.git
  2. 依存関係パッケージをインストールします。

    cd alibabacloud-adbpg-mcp-server
    uv pip install -e .
  3. MCP サーバーを構成します。プロジェクトフォルダに 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 サーバーをインストールします。

    uv pip install adbpg_mcp_server
  2. MCP サーバーを構成します。プロジェクトフォルダに 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"
        }
      }
    }

パラメーターの説明

説明

Alibaba Cloud Model Studio の base_url とサポートされているモデルのリストについては、「製品紹介」をご参照ください。

カテゴリ

環境変数

説明

データベース接続

ADBPG_HOST

データベースのホストアドレス。

ADBPG_PORT

データベースのポート。

ADBPG_USER

データベースのユーザー名。

ADBPG_PASSWORD

データベースのパスワード。

ADBPG_DATABASE

データベースの名前。

GraphRAG

GRAPHRAG_API_KEY

GraphRAG の API キー。

GRAPHRAG_BASE_URL

GraphRAG が使用する LLM の URL。

GRAPHRAG_LLM_MODEL

GraphRAG が使用する LLM の名前。

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

長期記憶が使用する LLM の API キー。

LLMEMORY_BASE_URL

長期記憶が使用する LLM の URL。

LLMEMORY_LLM_MODEL

長期記憶が使用する LLM の名前。

LLMEMORY_EMBEDDING_MODEL

長期記憶が使用する埋め込みモデル。

ステップ 3: クライアントスクリプトの作成と実行

main.py ファイルを作成し、次のサンプルコードを追加します。利用可能な機能の詳細については、「MCP サーバーがサポートするツール」をご参照ください。

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

# stdio 接続用のサーバーパラメーターを作成する
server_params = StdioServerParameters(
    # サーバーで実行するコマンド。uv を使用して adbpg-mcp-server を実行する
    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": "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")

            # 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, 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.

MCP サーバーがサポートするツール

カテゴリ

ツール

説明

データベース操作

execute_select_sql

SELECT SQL クエリを AnalyticDB PostgreSQL インスタンスで実行します。

execute_dml_sql

DML (INSERTUPDATEDELETE) SQL 文を AnalyticDB PostgreSQL インスタンスで実行します。

execute_ddl_sql

DDL (CREATEALTERDROP) SQL 文を AnalyticDB PostgreSQL インスタンスで実行します。

analyze_table

テーブルデータを収集します。

explain_query

クエリの実行計画を取得します。

GraphRAG 操作

adbpg_graphrag_upload

テキストのチャンク化、ベクター生成、知識グラフの抽出などの操作のために、ファイルを GraphRAG にアップロードします。

adbpg_graphrag_query

指定されたクエリモードに基づいてクエリを GraphRAG に送信し、結果を返します。

LLM 長期記憶操作

adbpg_llm_memory_add

LLM の長期記憶情報を作成または追加します。

adbpg_llm_memory_get_all

特定の UserRun、または Agent のすべてのメモリを取得します。

adbpg_llm_memory_search

指定された query に基づいて、特定の UserRun、または Agent のすべてのメモリを取得します。

adbpg_llm_memory_delete_all

特定の UserRun、または Agent のすべてのメモリを削除します。

データベース操作

execute_select_sql

  • 説明: SELECT SQL クエリを AnalyticDB PostgreSQL インスタンスで実行します。

  • パラメーター: SELECT SQL クエリ。

  • 戻り値: JSON 形式のクエリ結果。

execute_dml_sql

  • 説明: DML (INSERTUPDATEDELETE) SQL 文を AnalyticDB PostgreSQL インスタンスで実行します。

  • パラメーター: DML SQL 文。

  • 戻り値: 実行結果。

execute_ddl_sql

  • 説明: DDL (CREATEALTERDROPTRUNCATE) SQL 文を AnalyticDB PostgreSQL インスタンスで実行します。

  • パラメーター: DDL SQL 文。

  • 戻り値: 実行結果。

analyze_table

  • 説明: テーブルに関する統計を収集します。

  • パラメーター:

    • schema (text): スキーマ。

    • table (text): テーブル名。

  • explain 操作の結果を返します。

explain_query

  • 説明: クエリの実行計画を取得します。

  • パラメーター: explain SQL 文。

  • 戻り値: 実行結果。

GraphRAG 操作

adbpg_graphrag_upload

  • 説明: テキストのチャンク化、ベクター生成、知識グラフの抽出などの操作のために、ファイルを GraphRAG にアップロードします。

  • パラメーター:

    • filename (text): ファイル名。

    • context (text): ファイルの内容。

  • 戻り値: 実行結果。

  • 例:

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

adbpg_graphrag_query

  • 説明: 指定されたクエリモードに基づいてクエリを GraphRAG に送信し、結果を返します。

  • パラメーター:

    • query_str (text): クエリする質問。

    • query_mode (text): クエリモード。デフォルト値は mix です。有効な値は次のとおりです:

      • bypass: ベクター検索や知識グラフ検索を使用せずに、LLM に直接クエリします。

      • naive: ベクター検索のみを使用して関連知識を取得し、参照用に LLM に提供します。

      • local: 知識グラフのエンティティノードのみを使用して関連知識を取得し、参照用に LLM に提供します。

      • global: 知識グラフのリレーションシップエッジのみを使用して関連知識を取得し、参照用に LLM に提供します。

      • hybrid: 知識グラフのエンティティノードとリレーションシップエッジの両方を使用して関連知識を取得し、参照用に LLM に提供します。

      • mix (デフォルト): ベクターマッチングと知識グラフの両方を使用して関連知識を取得し、参照用に LLM に提供します。

    • start_search_node_id: tree クエリモードを使用する場合は、開始する決定木ノードの ID を指定します。

  • 戻り値: response (text)。GraphRAG によって取得された内容と元の質問に基づいて、LLM からの応答。

  • 例:

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

LLM 長期記憶操作

adbpg_llm_memory_add

  • 説明: LLM の長期記憶情報を作成または追加します。

  • パラメーター:

    • messages (json): 記憶する情報。

    • user_id (text): ユーザー ID。

    • run_id (text): 実行 ID。

    • agent_id (text): エージェント ID。

    • metadata (json): メモリプロパティを拡張するための追加のメタデータ。

    • memory_type (text): メモリタイプ。サポートされているタイプは semantic_memoryepisodic_memoryprocedural_memory です。通常、このパラメーターを指定する必要はありません。ただし、AI エージェントのメモリの場合は、procedural_memory に設定します。

    • prompt (text): 関連するプロンプトまたはコンテキスト。

    user_idrun_id、または agent_id のうち少なくとも 1 つを提供する必要があります。

  • 戻り値: result (json)。idmemoryevent などの情報を含む実行結果。

  • 例:

    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);
    
    -- 戻り値
    {'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

  • 説明: 特定の UserRun、または 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 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

  • 説明: 指定された query に基づいて、特定の UserRun、または Agent のすべてのメモリを取得します。

  • パラメーター:

    • query (text): クエリのテキスト内容。

    • user_id (text): ユーザー ID。

    • run_id (text): 実行 ID。

    • agent_id (text): エージェント ID。

    • filter (json): JSON 形式の追加のフィルター条件 (オプション)。

  • 戻り値: result (json)。実行結果。

  • 例:

    adbpg_llm_memory_search('Can you recommend some sports and related locations for this weekend?', '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 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

  • 説明: 特定の UserRun、または 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'}