5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Amazon Bedrock AgentCoreでADKを呼び出してみる

Last updated at Posted at 2025-10-18

この記事について

2025年10月13日、 Amazon Bedrock AgentCoreがGA(一般提供開始)されました。

AgentCore Memory, AgentCore Identity, AgentCore Gateway, AgentCore Code Interpreter, AgentCore Observability など複数の構成要素からなるAmazon Bedrock AgentCoreですが、多様なエージェントフレームワークを呼び出すことができる点に着目し、
本記事では、Google Agent Development Kit(以後ADKと表記)で作成した検索エージェントをAmazon Bedrock AgentCoreでホストして呼び出してみました。

手順

今回は 以下リポジトリにADKを呼び出すサンプルコードがありましたので、こちらを参考にさせていただき検索エージェントを作成してみることとします。

環境作成

Setup Instructionsの項に記載があるため、ここでは環境構築の手順は割愛します。2. Install Requirementsを行い、

agentcore launch --env GEMINI_API_KEY=your-gemini-api-key

を実施した前提で解説します。

事前にGemini APIキーを発行しておく必要があります。詳細はGemini API キーを使用するの項を参考に、Gemini API Keyの払い出しを行なってください。

今回作成されるエージェント

adk/ディレクトリの階層に格納されているadk_agent_google_search.pyがエージェントの中身となります。
ADKのビルトインツールである、google_search_toolsを使用し、ユーザーの指示に対してGoogle検索を行い回答を行うエージェントです。

日本語の回答を強制させるため、The Answer must be in Japanese.instruction引数で指定している指示に追加しておきます。(これを指定しておかないと英語で回答してしまうことが多かったため)

root_agent = Agent(
    model="gemini-2.0-flash",
    name="openai_agent",
    description="Agent to answer questions using Google Search.",
-    instruction="I can answer your questions by searching the internet. Just ask me anything!",
+    instruction="I can answer your questions by searching the internet. Just ask me anything!The Answer must be in Japanese.
    # google_search is a pre-built tool which allows the agent to perform Google searches.
    tools=[google_search],
)
adk_agent_google_search.py
import asyncio

from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools import google_search
from google.genai import types

# adapted form https://google.github.io/adk-docs/tools/built-in-tools/#google-search

APP_NAME = "google_search_agent"
USER_ID = "user1234"

# Agent Definition
# Add your GEMINI_API_KEY
root_agent = Agent(
    model="gemini-2.0-flash",
    name="openai_agent",
    description="Agent to answer questions using Google Search.",
    instruction="I can answer your questions by searching the internet. Just ask me anything! The Answer must be in Japanese.",
    # google_search is a pre-built tool which allows the agent to perform Google searches.
    tools=[google_search],
)


# Session and Runner
async def setup_session_and_runner(user_id, session_id):
    session_service = InMemorySessionService()
    session = await session_service.create_session(
        app_name=APP_NAME, user_id=user_id, session_id=session_id
    )
    runner = Runner(
        agent=root_agent, app_name=APP_NAME, session_service=session_service
    )
    return session, runner


# Agent Interaction
async def call_agent_async(query, user_id, session_id):
    content = types.Content(role="user", parts=[types.Part(text=query)])
    session, runner = await setup_session_and_runner(user_id, session_id)
    events = runner.run_async(
        user_id=user_id, session_id=session_id, new_message=content
    )

    async for event in events:
        if event.is_final_response():
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)

    return final_response


from bedrock_agentcore.runtime import BedrockAgentCoreApp

app = BedrockAgentCoreApp()


@app.entrypoint
def agent_invocation(payload, context):
    return asyncio.run(
        call_agent_async(
            payload.get("prompt", "what is Bedrock Agentcore Runtime?"),
            payload.get("user_id", USER_ID),
            context.session_id,
        )
    )


app.run()

Amazon Bedrock AgentCoreにデプロイされたエージェントを呼び出す

ターミナルからエージェントを呼び出してみます。"What is Amazon Bedrock Agentcore Runtime?"
と言う質問をしたところ、下記のように回答を得ることができました。

$ agentcore invoke '{"prompt": "What is Amazon Bedrock Agentcore Runtime?"}'  
$ agentcore invoke '{"prompt": "What is Amazon Bedrock Agentcore Runtime?"}'                   
╭──────────────────────────────────────────────────────────────────────────────────── adk_agent_google_search ─────────────────────────────────────────────────────────────────────────────────────╮
│ Session: fddb3ee7-6e1e-4277-8bb2-2f94cc7bf04f                                                                                                                                                    │
│ Request ID: e9326187-7fea-44cd-9942-172e86b026c1                                                                                                                                                 │
│ ARN: arn:aws:bedrock-agentcore:us-east-1:<your-account-id>:runtime/adk_agent_google_search-IyHkNO6FhP                                                                                                 │
│ Logs: aws logs tail /aws/bedrock-agentcore/runtimes/adk_agent_google_search-IyHkNO6FhP-DEFAULT --log-stream-name-prefix "2025/10/18/[runtime-logs]" --follow                                     │
│       aws logs tail /aws/bedrock-agentcore/runtimes/adk_agent_google_search-IyHkNO6FhP-DEFAULT --log-stream-name-prefix "2025/10/18/[runtime-logs]" --since 1h                                   │
│ GenAI Dashboard: https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#gen-ai-observability/agent-core                                                                                 │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

Response:
Amazon Bedrock AgentCore Runtimeは、AWSが提供する、AIエージェントとツールをデプロイおよびスケーリングするために特化して構築された、セキュアなサーバーレス実行環境です。

主な特徴は以下の通りです。
*   **サーバーレスでスケーラブル**:インフラストラクチャの管理オーバーヘッドなしに、需要に基づいて自動的にスケーリングされます。
*   **フレームワークとモデルに依存しない**:LangGraph、CrewAI、Strands Agentsなどのオープンソースフレームワーク、およびAmazon 
Bedrock、OpenAI、Geminiなどのあらゆるプロトコルやモデルを使用できます。
*   
**セッション分離とセキュリティ**:各ユーザーの会話を専用のマイクロVMで実行することで、データの漏洩やセッション間の汚染を防ぐ、エンタープライズグレードのセキュリティと完全なセッション分離を提供���
ます。
*   **長時間の実行をサポート**:リアルタイムの対話だけでなく、最大8時間の長時間実行タスクもサポートしており、複雑なワークフローに適しています。
*   **組み込みのアイデンティティとアクセス管理**:AgentCore Identityと連携し、AIエージェントの安全でスケーラブルな認証と認可機能を提供します。
*   **オブザーバビリティ**:エージェントの動作を監視するための組み込みメトリクスを提供し、Amazon 
CloudWatchやOpenTelemetry互換のダッシュボードを通じてリアルタイムのパフォーマンスインサイトを提供します。

Amazon Bedrock 
AgentCoreは、AIエージェントをプロトタイプから本番環境へ安全かつスケーラブルに移行させることを目的とした、包括的なプラットフォームの一部です。これにより、開発者はインフラストラクチャの管理に煩わさ
れる��となく、ビジネスロジックとイノベーションに集中できます。

Streamlit経由で呼び出す

ターミナルから呼び出すことが確認できたので、続いてはStreamlitで呼び出してみます。

requirements.txtに以下を追加し、

$ uv pip install -r requirements.txt

を実行します。

requirements.txt 追記箇所
google-adk
bedrock-agentcore
bedrock-agentcore-starter-toolkit
opentelemetry-sdk 
opentelemetry-exporter-otlp-proto-http
+++ streamlit
+++ boto3
+++ python-dotenv

続いてadk/ の階層に任意の名前でpythonファイルを作成します。(ここではapp.pyとします)

事前準備として、adk/の階層に.envを作成し、以下のように環境変数を定義しておきます。

AGENT_RUNTIME_ARN="arn:aws:bedrock-agentcore:<region-name>:<account-id>:runtime/<agent-name>"
app.py
import json
import os
import time
import uuid

import boto3
import streamlit as st
from dotenv import load_dotenv

# .envファイルから環境変数を読み込み
load_dotenv()

# bedrock-agentcoreクライアントの初期化
agent_core_client = boto3.client("bedrock-agentcore", region_name="us-east-1")

# セッションIDの定義 (一意の値を生成)
session_id = str(int(time.time())) + "_" + str(uuid.uuid4()).replace("-", "")


st.title("Google Search Agent")
st.write("Bedrock AgentCoreでホストするGoogle Search Agent サンプル")

runtime_arn = os.getenv("AGENT_RUNTIME_ARN")
if not runtime_arn:
    runtime_arn = st.text_input(label="AgentRuntime arnを入力してください")

if prompt := st.chat_input():
    if not runtime_arn:
        st.error("AgentRuntime ARNを設定してください")
    else:
        with st.chat_message("user"):
            st.write(prompt)

        with st.spinner("処理中..."):
            response = agent_core_client.invoke_agent_runtime(
                agentRuntimeArn=runtime_arn,
                runtimeSessionId=session_id,
                payload=json.dumps({"prompt": prompt}),
                qualifier="DEFAULT",
            )

            with st.chat_message("assistant"):
                try:
                    # レスポンスを読み取り
                    response_body = response["response"].read()

                    # バイトか文字列かをチェックしてデコード
                    if isinstance(response_body, bytes):
                        response_text = response_body.decode("utf-8")
                    else:
                        response_text = response_body

                    # JSONエスケープされた文字列をデコード
                    try:
                        # ダブルクォートで囲まれた文字列をJSONとしてパース
                        clean_text = json.loads(response_text)
                        # \nを改行に変換
                        formatted_text = clean_text.replace("\\n", "\n")
                        st.markdown(formatted_text)
                    except json.JSONDecodeError:
                        # JSONでない場合はそのまま表示
                        st.write(response_text)

                except Exception as e:
                    st.error(f"Error: {e}")

実行結果

$ uv run streamlit run app.py 
# localhost:8501が立ち上がる

画面上で今日のニュースについてジャンル別に教えてください。と質問をしたところ、指示通り今日(記事執筆時点: 2025/10/18)のニュースについて検索を行い、回答を返却してくれていることがわかります。
スクリーンショット 2025-10-18 20.43.11.png

まとめ

簡単な検証ではありますが、今回はAmazon Bedrock AgentCore上で、ADKで作成した検索エージェントをホストし、それをStreamlit上で呼び出し、回答を得られるようにする、ということを試してみました。(※ストリーミングでのレスポンス表示も試みましたが、今回はうまくいかなかったため、今後調査を進める予定です。)
他ベンダー製のエージェントフレームワークを容易に統合できる点で開発者体験が良いなと思いました。
また、開発者が使いたいフレームワークを自由に選べるようになることで、アイデア次第でより柔軟かつ拡張性の高いAIエージェント開発が可能になると感じました。

参照文献

  • boto3ドキュメント(bedrock-agentcore.invoke_agent_runtime

5
0
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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?