0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AgentCore GatewayにデプロイしたBedorock Knowledge Base検索ツールをAgentCore Runtimeから呼び出す

0
Posted at

はじめに

Bedrock Knowledge Baseを利用するAgentic RAGを実装する場合、Strands Agentsライブラリの strands_tools.retrieve で直接Bedrock Knowledge BaseのRetrieve APIを呼び出すことが一般的です。
シングルエージェント、かつ使用するツールも少ない場合、シンプルなRAGが構成できるというメリットがあります。

これに対して、本記事ではBedrock Knowledge Baseを検索するlambda関数をMCP互換ツールとしてAgentCore Gatewayにデプロイし、AgentCore RuntimeにデプロイしたStrands Agentsから呼び出す方式の実装を紹介します。

構築するアーキテクチャは、下図のとおりです。

image.png

AgentCore Gateway経由でBedrock Knowledge Baseを検索するツールを呼び出すメリットには下記があります:

  • 認証・認可の一元管理: AgentCore Gatewayはインバウンド(エージェントからツールへのアクセス)とアウトバウンド(ツールからバックエンドサービスへの接続)の双方向認証モデルを提供しています。OAuthやIAMの認証を集約して、シンプルなセキュリティ設定が可能です
  • ツールの疎結合・ライフサイクル管理: AgetCore Gatewayはツールインフラとエージェントランタイムを分離し、エージェントを再デプロイせずにツールの追加や更新を可能にする構成をサポートしています。Knowledge Baseの差し替え(IDの変更、リージョンの変更、retrieveパラメータの調整など)をGateway側のターゲット設定だけで対応でき、Runtime上のエージェントコンテナを再ビルド・再デプロイする必要がありません
  • セマンティックツールディスカバリ: AgentCore Gatewayは x_amz_bedrock_agentcore_search というビルトインツールを提供し、エージェントが数百~数千のツールから最も適切なものをセマンティック検索で発見できます。Knowledge Baseのretireveツール以外にも多数のツールを併用する環境では、すべてのツール定義をプロンプトに含める代わりに、Gatewayのセマンティック検索を使用することで、ツール過多による精度の低下を防ぐことができます
  • マルチエージェント・マルチテナント環境での共有: AgentCore Gatewayは複数のAPI、Lambda関数、ツールを単一のMCPエンドポイントに統合する役割を果たします。複数のエージェント(異なるチームやフレームワーク)が同じKnowledge Baseを利用する場合、Gatewayにツールを一元登録しておけば、各エージェントは同じMCPエンドポイントに接続するだけで利用が可能です
  • スロットリング・レート制御・監査ログ: AgentCore Gatewayにはスロットリングやレート制限、マルチテナント分離が組み込まれており、エージェントがスケールする際にバックエンドを保護します。また、包括的な監査ログによりコンプライアンスやトレーサビリティを確保できます

今回の大まかな実装の流れは下記のとおりです。

  • S3 Vectors + Bedrock Knowledge BasesによるRAG機能実装
  • RAG機能をLambda関数でラップしてAgentCore Gatewayにデプロイ
  • Strands Agentsで実装したエージェントをAgentCore Runtimeにデプロイ

RAG機能実装

まず、S3 VectorsをベクトルストアとするBedrock Knowledge Baseを用いたRAG機能を実装します。

S3バケットの作成

AWSコンソール画面のAmazon S3で、汎用ストレージを作成します。

image-1.png

作成した汎用バケットに、RAGの検索対象とするドキュメントをアップロードします。
今回はサンプルとして、デジタル庁の資料を使用しました。

image-2.png

Bedrock Knowledge Basesの作成

Amazon Bedrockで、ベクトルストアを含むナレッジベースを作成します。

image-3.png

データソースとしてのS3のURIに、前段で作成した汎用ストレージを指定します。

image-4.png

今回は埋め込みモデルとして、Titan Text Embeddings v2を指定しました。
ベクトルデータベースで「新しいベクトルストアをクイック作成」を選択し、ベクトルストアとして「Amazon S3 Vectors」を選択します。

image-5.png

RAG機能のテスト

汎用バケットに追加したドキュメンをベクトル表現に埋め込み、インデックス化するために、Amazon Bedrock画面で「同期」を実行します。

image-6.png

データソースの同期が完了後、作成したAmazon Bedrockのナレッジベースをテストします。
生成モデルを選択後、プロンプトを送信し、応答を確認します。

image-7.png

ツールのデプロイ

上記で作成したBedrock Knowledge Baseからretrieveする機能をLambda関数にラップし、AgentCore Gatewayにデプロイして、MCP互換ツールに変換します。

Lambda関数の作成

Lambda関数のコードは下記のとおりです。

handler.py
"""
AgentCore Gateway Lambda Target: Bedrock Knowledge Bases Retrieve Tool
----------------------------------------------------------------------
This Lambda function is invoked by AgentCore Gateway as an MCP-compatible tool.
It supports two operations:
  1. retrieve       - Semantic search only (returns raw chunks)
  2. retrieve_and_generate - RAG (retrieves + generates an answer with citations)

Environment Variables:
  KNOWLEDGE_BASE_ID  - Bedrock Knowledge Base ID (e.g. "ABCDE12345")
  MODEL_ARN          - Model ARN for RAG generation
                       (e.g. "arn:aws:bedrock:ap-northeast-1::foundation-model/anthropic.claude-sonnet-4-20250514")
  DEFAULT_TOP_K      - Default number of results to retrieve (default: 5)
  AWS_REGION         - AWS Region (set automatically by Lambda runtime)
"""

import json
import logging
import os
from typing import Any

import boto3

logger = logging.getLogger()
logger.setLevel(logging.INFO)

# ---------- Clients (initialized once per cold start) ----------
bedrock_agent_runtime = boto3.client("bedrock-agent-runtime")

# ---------- Configuration ----------
KNOWLEDGE_BASE_ID = os.environ["KNOWLEDGE_BASE_ID"]
MODEL_ARN = os.environ.get(
    "MODEL_ARN",
    f"arn:aws:bedrock:{os.environ.get('AWS_REGION', 'ap-northeast-1')}"
    "::foundation-model/anthropic.claude-sonnet-4-20250514",
)
DEFAULT_TOP_K = int(os.environ.get("DEFAULT_TOP_K", "5"))


# ==================== Tool Schema Definitions ====================
# These are referenced when registering this Lambda as a Gateway target.
# They are NOT used at runtime but documented here for clarity.

TOOL_SCHEMAS = [
    {
        "name": "retrieve",
        "description": (
            "Perform semantic search against the knowledge base. "
            "Returns the most relevant text chunks with source metadata. "
            "Use this when you need raw source documents without LLM-generated answers."
        ),
        "inputSchema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "The natural language search query.",
                },
                "top_k": {
                    "type": "integer",
                    "description": "Number of results to return (1-20). Default: 5.",
                },
                "filter": {
                    "type": "object",
                    "description": (
                        "Optional metadata filter. Example: "
                        '{"equals": {"key": "department", "value": "engineering"}}'
                    ),
                },
            },
            "required": ["query"],
        },
        "outputSchema": {
            "type": "object",
            "properties": {
                "results": {
                    "type": "array",
                    "description": "Array of retrieved text chunks with metadata.",
                },
                "result_count": {
                    "type": "integer",
                    "description": "Number of results returned.",
                },
            },
        },
    },
    {
        "name": "retrieve_and_generate",
        "description": (
            "Query the knowledge base and generate a natural language answer "
            "with citations from the retrieved sources. "
            "Use this when you need a synthesized answer rather than raw chunks."
        ),
        "inputSchema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "The natural language question to answer.",
                },
                "top_k": {
                    "type": "integer",
                    "description": "Number of source chunks to retrieve (1-20). Default: 5.",
                },
                "filter": {
                    "type": "object",
                    "description": (
                        "Optional metadata filter. Example: "
                        '{"equals": {"key": "department", "value": "engineering"}}'
                    ),
                },
            },
            "required": ["query"],
        },
        "outputSchema": {
            "type": "object",
            "properties": {
                "answer": {
                    "type": "string",
                    "description": "Generated answer text.",
                },
                "citations": {
                    "type": "array",
                    "description": "Source citations for the generated answer.",
                },
            },
        },
    },
]


# ==================== Handler ====================

def lambda_handler(event: dict[str, Any], context: Any) -> dict[str, Any]:
    """
    Entry point invoked by AgentCore Gateway.

    Event format from Gateway (Lambda target):
      The event body IS the tool's input parameters directly.
      e.g. {"query": "What is S3 Vectors?", "top_k": 3}

    The Gateway context object contains metadata like:
      - bedrockAgentCoreToolName: "KBTarget___retrieve"
      - bedrockAgentCoreGatewayId, bedrockAgentCoreTargetId, etc.
    """
    logger.info("Event: %s", json.dumps(event, default=str))
    logger.info("Context: %s", json.dumps(
        {k: v for k, v in (context.__dict__.items() if hasattr(context, '__dict__') else [])},
        default=str,
    ))

    # --- Determine which tool was called ---
    # Gateway sets the tool name in the context object.
    # Format: "{target_name}___{tool_name}"
    # We need to extract just the tool_name part.
    tool_name_raw = ""
    if hasattr(context, "client_context") and context.client_context:
        tool_name_raw = getattr(context.client_context, "custom", {}).get(
            "bedrockAgentCoreToolName", ""
        )

    # Fallback: check if tool_name is embedded in the event
    # (varies by Gateway SDK version)
    if not tool_name_raw:
        tool_name_raw = event.pop("_tool_name", "")

    # Strip target prefix: "KBTarget___retrieve" -> "retrieve"
    tool_name = tool_name_raw.split("___")[-1] if "___" in tool_name_raw else tool_name_raw

    # If still empty, infer from event keys
    if not tool_name:
        tool_name = "retrieve_and_generate" if "query" in event else "retrieve"

    logger.info("Resolved tool_name: %s", tool_name)

    try:
        if tool_name == "retrieve":
            return handle_retrieve(event)
        elif tool_name == "retrieve_and_generate":
            return handle_retrieve_and_generate(event)
        else:
            return _error_response(f"Unknown tool: {tool_name}")
    except Exception as e:
        logger.exception("Tool execution failed")
        return _error_response(str(e))


# ==================== Retrieve (semantic search only) ====================

def handle_retrieve(event: dict) -> dict:
    """Call Bedrock Knowledge Bases Retrieve API."""
    query = event["query"]
    top_k = min(int(event.get("top_k", DEFAULT_TOP_K)), 20)
    metadata_filter = event.get("filter")

    retrieval_config: dict[str, Any] = {
        "vectorSearchConfiguration": {
            "numberOfResults": top_k,
        }
    }
    if metadata_filter:
        retrieval_config["vectorSearchConfiguration"]["filter"] = metadata_filter

    response = bedrock_agent_runtime.retrieve(
        knowledgeBaseId=KNOWLEDGE_BASE_ID,
        retrievalQuery={"text": query},
        retrievalConfiguration=retrieval_config,
    )

    results = []
    for item in response.get("retrievalResults", []):
        result = {
            "text": item.get("content", {}).get("text", ""),
            "score": float(item.get("score", 0)),
            "source": _extract_source_uri(item),
            "metadata": item.get("metadata", {}),
        }
        results.append(result)

    return {
        "results": results,
        "result_count": len(results),
    }


# ==================== Retrieve and Generate (RAG) ====================

def handle_retrieve_and_generate(event: dict) -> dict:
    """Call Bedrock Knowledge Bases RetrieveAndGenerate API."""
    query = event["query"]
    top_k = min(int(event.get("top_k", DEFAULT_TOP_K)), 20)
    metadata_filter = event.get("filter")

    kb_config: dict[str, Any] = {
        "knowledgeBaseId": KNOWLEDGE_BASE_ID,
        "modelArn": MODEL_ARN,
        "retrievalConfiguration": {
            "vectorSearchConfiguration": {
                "numberOfResults": top_k,
            }
        },
    }
    if metadata_filter:
        kb_config["retrievalConfiguration"]["vectorSearchConfiguration"]["filter"] = (
            metadata_filter
        )

    response = bedrock_agent_runtime.retrieve_and_generate(
        input={"text": query},
        retrieveAndGenerateConfiguration={
            "type": "KNOWLEDGE_BASE",
            "knowledgeBaseConfiguration": kb_config,
        },
    )

    answer = response.get("output", {}).get("text", "")
    citations = []
    for citation_group in response.get("citations", []):
        gen_part = citation_group.get("generatedResponsePart", {})
        text_part = gen_part.get("textResponsePart", {})
        refs = []
        for ref in citation_group.get("retrievedReferences", []):
            refs.append({
                "text": ref.get("content", {}).get("text", ""),
                "source": _extract_source_uri(ref),
            })
        citations.append({
            "cited_text": text_part.get("text", ""),
            "span": text_part.get("span", {}),
            "references": refs,
        })

    return {
        "answer": answer,
        "citations": citations,
    }


# ==================== Helpers ====================

def _extract_source_uri(item: dict) -> str:
    """Extract source URI from a retrieval result or reference."""
    location = item.get("location", {})
    loc_type = location.get("type", "")
    if loc_type == "S3":
        return location.get("s3Location", {}).get("uri", "")
    elif loc_type == "CUSTOM":
        return location.get("customDocumentLocation", {}).get("id", "")
    return ""


def _error_response(message: str) -> dict:
    """Return a structured error response."""
    return {
        "error": True,
        "message": message,
    }

AWSコンソールで、「設定」>「環境変数」に環境変数を指定します。

キー
DEFAULT_TOP_K 5
KNOWLEDGE_BASE_ID [your_knowledgebase_id]
MODEL_ARN arn:aws:bedrock:ap-northeast-1:[your-account-id]:inference-profile/jp.anthropic.claude-haiku-4-5-20251001-v1:0

AgentCore Gatewayにデプロイ

作成したLambda関数をAgentCoreにMCP互換ツールとしてデプロイします。

Gatewayの作成

image-8.png

ターゲットの作成

image-9.png

  • ターゲットタイプ:Lambda ARN
  • Lambda ARN: lambdaのARNをコピー
  • インラインスキーマエディタ
{
    "name": "retrieve",
    "description": "Perform semantic search against the knowledge base. Returns relevant text chunks with metadata and relevance scores.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "query":  { "type": "string",  "description": "Natural language search query" },
        "top_k":  { "type": "integer", "description": "Number of results (1-20, default 5)" },
        "filter": { "type": "object",  "description": "Optional metadata filter" }
      },
      "required": ["query"]
    }
  }

ターゲットを追加します。

  • ターゲットタイプ:Lambda ARN
  • Lambda ARN: lambdaのARNをコピー
  • インラインスキーマエディタ
{
    "name": "retrieve_and_generate",
    "description": "Query the knowledge base and generate a natural language answer with citations from retrieved sources.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "query":  { "type": "string",  "description": "Natural language question to answer" },
        "top_k":  { "type": "integer", "description": "Number of source chunks (1-20, default 5)" },
        "filter": { "type": "object",  "description": "Optional metadata filter" }
      },
      "required": ["query"]
    }
  }

エージェントのデプロイ

Strands Agentsライブラリを使ってエージェントを実装し、AgentCore Runtimeにデプロイします。

Secrets Managerの設定

AgentCore RuntimeにデプロイしたあとのStrands Agentsベースのエージェントが環境変数を使用できるように、Secrets Managerに登録します。

agentcore-kb/config という名前で、新しいシークレットを作成します。
AgentCore Gatewayとともに作成されたAmazon Cognitoのユーザプールを参照しながら、値を登録します。

キー
GATEWAY_URL Gateway resource URLの値
COGNITO_CLIENT_ID アプリケーションクライアントのクライアントIDの値
COGNITO_CLIENT_SECRET アプリケーションクライアントのクライアントシークレットの値
COGNITO_DISCOVERY_URL 作成したAgentCore Gatewayの「インバウンドID」>「検出URL(Discovery URL)」の値
COGNITO_CUSTOM_SCOPE アプリケーションクライアントの「ログインページ」>「カスタムスコープ」の値

image-10.png

Strands Agentsの実装

AgentCore Runtimeが呼び出す関数を登録するためのでデコレータ @app.entrypointを付与して、Strands Agentsのコードを作成します。

app.py
from dotenv import load_dotenv
import base64
import json
import logging
import os

import boto3
import requests
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands import Agent
from strands.models import BedrockModel
from strands.tools.mcp import MCPClient
from mcp.client.streamable_http import streamablehttp_client

load_dotenv()  # ローカル開発用(コンテナでは何もしない)

_secrets_cache = None

def get_secrets():
    global _secrets_cache
    if _secrets_cache is None:
        client = boto3.client("secretsmanager", region_name="ap-northeast-1")
        response = client.get_secret_value(SecretId="agentcore-kb/config")
        _secrets_cache = json.loads(response["SecretString"])
    return _secrets_cache

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

app = BedrockAgentCoreApp()

# ==================== Configuration ====================
SYSTEM_PROMPT = """\
You are a knowledgeable assistant with access to an internal knowledge base.

When answering questions:
1. First use the KBTarget___retrieve_and_generate tool to search the knowledge base
   and generate an answer with citations.
2. If you need more specific source documents, use the KBTarget___retrieve tool
   to perform semantic search and inspect raw chunks.
3. Always cite your sources when the information comes from the knowledge base.
4. If the knowledge base does not contain relevant information, clearly state that.
"""


# ==================== Helpers ====================

def get_access_token():
    secrets = get_secrets()
    client_id = os.getenv("COGNITO_CLIENT_ID") or secrets["COGNITO_CLIENT_ID"]
    client_secret = os.getenv("COGNITO_CLIENT_SECRET") or secrets["COGNITO_CLIENT_SECRET"]
    discovery_url = os.getenv("COGNITO_DISCOVERY_URL") or secrets["COGNITO_DISCOVERY_URL"]
    custom_scope = os.getenv("COGNITO_CUSTOM_SCOPE") or secrets["COGNITO_CUSTOM_SCOPE"]

    # Basic 認証ヘッダ
    auth_header = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()

    # OIDC Discovery から token_endpoint を取得
    discovery_resp = requests.get(discovery_url, timeout=10)
    discovery_resp.raise_for_status()
    token_endpoint = discovery_resp.json()["token_endpoint"]

    # Client Credentials でアクセストークン取得
    token_headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": f"Basic {auth_header}",
    }
    token_data = {
        "grant_type": "client_credentials", 
        "scope": custom_scope
    }
    token_resp = requests.post(token_endpoint, headers=token_headers, data=token_data, timeout=10)
    token_resp.raise_for_status()
    return token_resp.json()["access_token"]


# ==================== Entrypoint ====================

@app.entrypoint
def invoke(payload):
    """
    AgentCore Runtime entry point.

    Expected payload:
      {"prompt": "Your question here"}

    Returns:
      Plain text response from the agent.
    """
    prompt = payload.get("prompt", "Hello!")
    logger.info("Received prompt: %s", prompt)

    # 1. Get OAuth token for Gateway
    access_token = get_access_token()

    # 2. Connect to Gateway via MCP
    secrets = get_secrets()
    gateway_url = os.environ.get("GATEWAY_URL") or secrets["GATEWAY_URL"]
    model_id = os.environ.get("MODEL_ID", "jp.anthropic.claude-haiku-4-5-20251001-v1:0")
    region = os.environ.get("AWS_REGION", "ap-northeast-1")

    transport = lambda: streamablehttp_client(
        gateway_url,
        headers={"Authorization": f"Bearer {access_token}"},
    )

    with MCPClient(transport) as mcp_client:
        tools = mcp_client.list_tools_sync()
        logger.info("Loaded %d tools from Gateway", len(tools))

        # 3. Create Agent
        model = BedrockModel(
            model_id=model_id,
            region_name=region,
        )
        agent = Agent(
            model=model,
            tools=tools,
            system_prompt=SYSTEM_PROMPT,
        )

        # 4. Invoke
        result = agent(prompt)

        # 5. Extract text response
        response_text = str(result)
        logger.info("Agent response length: %d chars", len(response_text))

        return response_text


if __name__ == "__main__":
    app.run()

Strands Agentsからツールを呼び出してテスト

下記のコマンドで、エージェントのコードを実行します。

python app.py

別タブでプロンプトを送信して、応答を確認します。

curl -X POST http://localhost:8080/invocations   -H "Content-Type: application/json"   -d '{"prompt": "ナレッジベースの情報をもとに、今後の取り組みについてまとめてください"}'
ナレッジベースの情報をもとに、今後の取り組みについてまとめました。

## 今後の取り組みのまとめ

### **1. 組織の方向性:「デジタル庁2.0へ」**

デジタル庁は、AI・データを最大限に活用する行政組織への転換を目指しており、デジタルファーストを発展させながら、世界をリードする官民一体の組織づくりを推進していく計画です。[^1]

### **2. 体制強化の重点**

**政策立案機能と内部開発機能の強化**(2024年開始)[^2]
- **官房機能の強化**:総括審議官の設置、官房機能と企画機能の分担明確化
- **内部開発機能の強化**(AI実装):
    - 研究開発、サービス開発、関係者共創の体制強化
    - 内部開発の環境やプロセスの整備
    
### **3. 重点的な取り組み**

以下の4つが掲げられています:[^3]

1. **AI・デジタル技術等のテクノロジーの徹底活用**
2. **AIフレンドリーな環境整備**
3. **競争・成長のための協調**
4. **DX推進力の強化**

### **4. 実現方法:「三位一体」のデジタル改革**

政策の企画・立案段階から、制度・業務・システムを一体として捉えたデジタル改革を推進し、デジタル化のメリットを実感できる分野を着実に増やしていく予定です。

### **5. 次世代行政組織の構築**

AI・データ活用を前提とした次世代の行政組織へ向けて:[^4]
- **利用者視点による関係者との共創**
- **変革力の確保**(企画・開発、業務プロセスの変革)
- **中長期の政策推進と社会実装**
- **成果の可視化と組織の継続改善**

---

[^1]: 「デジタル庁2.0へ」に基づき推進 - 2025年デジタル庁活動報告及び今後の取組
[^2]: 政策立案と内部開発の体制強化(2024年開始)- 2025年デジタル庁活動報告及び今後の取組
[^3]: 今後の取組の方向性と重点的な取組 - 2025年デジタル庁活動報告及び今後の取組
[^4]: 次世代の行政組織への転換 - 2025年デジタル庁活動報告及び今後の取組

AgentCore Runtimeにデプロイ

必要なライブラリをインストールしたのち、作成したStrands AgentsをAgentCore Runtimeにデプロイします。

pip install bedrock-agentcore-starter-toolkit
agentcore configure --entrypoint app.py

下記のようなメッセージが出力されます。

Configuring Bedrock AgentCore...
✓ Using file: app.py

🏷️  Inferred agent name: app
Press Enter to use this name, or type a different one (alphanumeric without '-')
Agent name [app]: kb_agent
✓ Using agent name: kb_agent

🔍 Detected dependency file: requirements.txt
Press Enter to use this file, or type a different path (use Tab for autocomplete):
Path or Press Enter to use detected dependency file: requirements.txt
✓ Using requirements file: requirements.txt

🚀 Deployment Configuration
Warning: Direct Code Deploy deployment unavailable (uv not found (install from: https://docs.astral.sh/uv/)). Falling 
back to Container deployment.
Select deployment type:
  1. Container - Docker-based deployment
✓ Deployment type: Container

🔐 Execution Role
Press Enter to auto-create execution role, or provide execution role ARN/name to use existing
Execution role ARN/name (or press Enter to auto-create):
✓ Will auto-create execution role

🏗️  ECR Repository
Press Enter to auto-create ECR repository, or provide ECR Repository URI to use existing
ECR Repository URI (or press Enter to auto-create):
✓ Will auto-create ECR repository

🔐 Authorization Configuration
By default, Bedrock AgentCore uses IAM authorization.
Configure OAuth authorizer instead? (yes/no) [no]:
✓ Using default IAM authorization

🔒 Request Header Allowlist
Configure which request headers are allowed to pass through to your agent.
Common headers: Authorization, X-Amzn-Bedrock-AgentCore-Runtime-Custom-*
Configure request header allowlist? (yes/no) [no]:
✓ Using default request header configuration
Configuring BedrockAgentCore agent: kb_agent

Memory Configuration
Tip: Use --disable-memory flag to skip memory entirely

No existing memory resources found in your account

Options:
  • Press Enter to create new memory
  • Type 's' to skip memory setup

Your choice:
✓ Short-term memory will be enabled (default)
  • Stores conversations within sessions
  • Provides immediate context recall

Optional: Long-term memory
  • Extracts user preferences across sessions
  • Remembers facts and patterns
  • Creates session summaries
  • Note: Takes 120-180 seconds to process

Enable long-term memory? (yes/no) [no]:
✓ Using short-term memory only
Will create new memory with mode: STM_ONLY
Memory configuration: Short-term memory only
Network mode: PUBLIC

⚠️ Platform mismatch: Current system is 'linux/amd64' but Bedrock AgentCore requires 'linux/arm64', so local builds 
won't work.
Please use default launch command which will do a remote cross-platform build using code build.For deployment other 
options and workarounds, see: https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/getting-started-custom.html

📄 Generated Dockerfile: /home/[username]/agentcore-kb/.bedrock_agentcore/kb_agent/Dockerfile
Setting 'kb_agent' as default agent
╭─────────────────────────────────────────────── Configuration Success ────────────────────────────────────────────────╮
│ Agent Details                                                                                                        │
│ Agent Name: kb_agent                                                                                                 │
│ Deployment: container                                                                                                │
│ Region: ap-northeast-1                                                                                               │
│ Account: <your-account-id>                                                                                           │
│                                                                                                                      │
│ Configuration                                                                                                        │
│ Execution Role: Auto-create                                                                                          │
│ ECR Repository: Auto-create                                                                                          │
│ Network Mode: Public                                                                                                 │
│ ECR Repository: Auto-create                                                                                          │
│ Authorization: IAM (default)                                                                                         │
│                                                                                                                      │
│                                                                                                                      │
│ Memory: Short-term memory (30-day retention)                                                                         │
│                                                                                                                      │
│                                                                                                                      │
│ 📄 Config saved to: /home/[username]/agentcore-kb/.bedrock_agentcore.yaml                                            │
│                                                                                                                      │
│ Next Steps:                                                                                                          │
│ agentcore deploy                                                                                                     │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

下記のコマンドでデプロイを実行します。

agentcore launch

Deployment completed successfully というメッセージが表示されれば成功です。

AgentCore Runtimeを呼び出してテストします。

agentcore invoke '{"ナレッジベースの情報をもとに、今後の取り組みについてまとめてください"}'
Response:
ナレッジベースの情報をもとに、今後の取り組みについてまとめました。

## 📋 今後の取り組みまとめ

### **1. 基本方向**
デジタル庁の今後の取り組みは、**「社会全体のデジタル改革推進」**に向かっており、行政のデジタル改革から社会全体へのデジタ
ル改革へシフトしています。また、**AIフレンドリーな国家の実現**を目指しています。

### **2. 将来計画:「デジタル庁2.0へ」**
- **AI・データの最大活用**:行政組織を強化し、AI・データを最大限に活用する体制を構築
- **官民一体の組織づくり**:世界をリードする組織開発を推進

### **3. 重点的な4つの取り組み**

1. **AI・デジタル技術等のテクノロジーの徹底活用**
2. **AIフレンドリーな環境整備**
3. **競争・成長のための協調**
4. **DX推進力の強化**

### **4. 改革アプローチ:「三位一体」戦略**
政策の企画・立案段階から、以下を統合的に推進:
- 💻 **システムの改革**
- 🔄 **業務の改革**
- 📋 **制度の改革**

### **5. 実現目標**
- 利用者視点のサービス拡充
- ストレスを感じない、やさしい公共サービスの実現
- 妊娠・出生からこども、引越し、就職、結婚、介護、死亡など、ライフイベントに合わせた公共サービスの提供
- **デジタル化のメリットを実感できる分野を着実に増やしていく**

これらの施策により、国民の生活体験を向上させ、より利便性の高い行政サービスの実現を目指しています。

おわりに

AgentCore GatewayにデプロイしたBedrock Knowledge Base検索ツールをAgentCore Runtimeから呼び出すことの確認ができました。

strands_tools.retrieveで直接Bedrock Knowledge BaseのRetrieve APIを呼び出すStrands AgentsコードをAgentCore Runtimeにデプロイする場合のほうが、Gatewayを経由しないことでレイテンシが低くなることや、追加コストが発生しないメリットもあります。
シンプルなRAG構成であれば、この方法で十分なケースは多いでしょう。

本記事で紹介した、Gateway経由でBedrock Knowledge Baseをretrieveする方法が活きるのは、複数のエージェントやチームでKnowledge Baseを共有する場合やツール数が多い場合、またはエンタープライズレベルのセキュリティ・ガバナンスが求められる場合、エージェントの再デプロイなしにツール構成を柔軟に変更したい場合などです。

要件によって、最適な実装方法を選定することが重要です。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?