Agent Development Kit(ADK)を使用して AI エージェントをビルドして Cloud Run にデプロイする

Agent Development Kit(ADK)フレームワークを使用すると、AI エージェントの作成、評価、デプロイを簡素化できます。ADK は、推論、計画、ツール利用を行えるエージェントを構築するための、モジュール式のコードファースト アプローチを提供します。

このチュートリアルでは、ADK for Python を使用して AI エージェントをビルドし、Cloud Run にデプロイする方法について説明します。このエージェントは、指定した都市の天気予報を取得します。

Google Cloud CLI を使用して ADK エージェントをホストする方法については、ADK ドキュメントの Cloud Run にデプロイするをご覧ください。

目標

費用

このドキュメントでは、課金対象である次の Google Cloudコンポーネントを使用します。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。

新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. Enable the Cloud Run Admin API, Vertex AI API, and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  7. Google Cloud プロジェクトで Cloud Run 開発環境を設定します。
  8. Agent Development Kit のドキュメントの手順に沿って ADK をインストールします。
  9. ドメイン制限の組織のポリシーでプロジェクトの未認証呼び出しが制限されている場合は、限定公開サービスのテストの説明に従って、デプロイされたサービスにアクセスする必要があります。

  10. 必要なロール

    AI エージェントを Cloud Run にデプロイするために必要な権限を取得するには、次の IAM ロールを付与するよう管理者に依頼してください。

    ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

    必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

サンプル アプリケーションを作成する

Python でアプリケーションを作成するには:

  1. parent_folder という名前の新しい親ディレクトリを作成し、そのディレクトリに移動します。

    mkdir parent_folder
    cd parent_folder
    
  2. parent_folder ディレクトリに、multi_tool_agent という名前の新しいサブディレクトリを作成し、そのディレクトリに移動します。

    mkdir multi_tool_agent
    cd multi_tool_agent
    
  3. エージェントをインポートするための __init__.py ファイルを作成します。

    from . import agent
    
  4. agent.py ファイルを作成して、指定された都市の時刻と天気に関する質問に回答するエージェントを定義します。

    import datetime
    from zoneinfo import ZoneInfo
    from google.adk.agents import Agent
    
    def get_weather(city: str) -> dict:
        """Retrieves the current weather report for a specified city.
    
        Args:
            city (str): The name of the city for which to retrieve the weather report.
    
        Returns:
            dict: status and result or error msg.
        """
        if city.lower() == "new york":
            return {
                "status": "success",
                "report": (
                    "The weather in New York is sunny with a temperature of 25 degrees"
                    " Celsius (77 degrees Fahrenheit)."
                ),
            }
        else:
            return {
                "status": "error",
                "error_message": f"Weather information for '{city}' is not available.",
            }
    
    def get_current_time(city: str) -> dict:
        """Returns the current time in a specified city.
    
        Args:
            city (str): The name of the city for which to retrieve the current time.
    
        Returns:
            dict: status and result or error msg.
        """
    
        if city.lower() == "new york":
            tz_identifier = "America/New_York"
        else:
            return {
                "status": "error",
                "error_message": (
                    f"Sorry, I don't have timezone information for {city}."
                ),
            }
    
        tz = ZoneInfo(tz_identifier)
        now = datetime.datetime.now(tz)
        report = (
            f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
        )
        return {"status": "success", "report": report}
    
    root_agent = Agent(
        name="weather_time_agent",
        model="gemini-2.0-flash",
        description=(
            "Agent to answer questions about the time and weather in a city."
        ),
        instruction=(
            "You are a helpful agent who can answer user questions about the time and weather in a city."
        ),
        tools=[get_weather, get_current_time],
    )
    
  5. .env ファイルを作成し、次の変数を追加します。

    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_CLOUD_PROJECT=PROJECT_ID
    GOOGLE_CLOUD_LOCATION=REGION
    

    次のように置き換えます。

    • PROJECT_ID: Google Cloud プロジェクト ID。
    • REGION: サービスをデプロイする予定のリージョン。
  6. 親フォルダのディレクトリ parent_folder に移動し、google-adk 依存関係を追加する requirements.txt ファイルを作成します。

    google-adk
    

    ソース プロジェクトには次の構造が含まれています。

    parent_folder/
    ├── requirements.txt
    └── multi_tool_agent/
        ├── __init__.py
        ├── agent.py
        └── .env
    

これでアプリが完成し、デプロイできるようになりました。

ソースから Cloud Run にデプロイする

ソースからのデプロイでは、ソースコードからコンテナ イメージが自動的にビルドされて、デプロイされます。

  1. ソースコード ディレクトリ(parent_folder)で、次のコマンドを使用して Cloud Run にデプロイします。

    gcloud beta run deploy --source .
    1. サービス名の入力を求められたら、Enter キーを押して、デフォルトの名前(weather-agent など)を受け入れます。

    2. プロジェクトで追加の API(Artifact Registry API など)を有効にするよう求められたら、y を押して応答します。

    3. リージョンの入力を求められたら、任意のリージョンeurope-west1 など)を選択します。

    4. 指定したリージョンにリポジトリを作成するように求められたら、y を押します。

    5. 公開アクセスを許可するように求められたら、y を押します。ドメイン制限の組織のポリシーが原因でこのメッセージが表示されない場合があります。詳細については、始める前にのセクションをご覧ください。

    デプロイが完了するまで少しお待ちください。成功すると、コマンドラインにサービス URL が表示されます。サービス URL から /list-apps に移動します。例: https://weather-agent-123456789101.us-central1.run.app/list-apps

エージェントを実行する

ADK エージェントをクエリするには、次の curl コマンドを実行します。

  1. アプリのリストを取得するには、次のコマンドを実行します。

    curl -X GET SERVICE_URL/list-apps
    

    SERVICE_URL は、デプロイされたサービスの URL に置き換えます。

  2. セッションを開始するには、次のコマンドを実行します。

    curl -X POST SERVICE_URL/apps/multi_tool_agent/users/u_123/sessions/s_123 -H "Content-Type: application/json" -d '{"key1": "value1", "key2": 42}'
    
  3. エージェントをクエリするには、次のコマンドを実行します。

    curl -X POST SERVICE_URL/run \
    -H "Content-Type: application/json" \
    -d "{\"appName\": \"multi_tool_agent\",\"userId\": \"u_123\",\"sessionId\": \"s_123\",\"newMessage\": { \"role\": \"user\", \"parts\": [{ \"text\": \"What's the weather in New York today?\" }]}}"
    

エージェントは、クエリの結果として天気情報を返します。

サポートされている curl コマンドの詳細と例については、ADK ドキュメントのAPI サーバーを使用するをご覧ください。

クリーンアップ

Google Cloud アカウントで追加料金が発生しないようにするには、このチュートリアルでデプロイしたすべてのリソースを削除します。

プロジェクトを削除する

このチュートリアル用に新規プロジェクトを作成した場合は、そのプロジェクトを削除します。既存のプロジェクトを使用し、このチュートリアルで行った変更を加えずに残す場合は、チュートリアル用に作成したリソースを削除します。

課金をなくす最も簡単な方法は、チュートリアル用に作成したプロジェクトを削除することです。

プロジェクトを削除するには:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

チュートリアル リソースを削除する

  1. このチュートリアルでデプロイした Cloud Run サービスを削除します。Cloud Run サービスの費用は、リクエストを受け取るまでは発生しません。

    Cloud Run サービスを削除するには、次のコマンドを実行します。

    gcloud run services delete SERVICE-NAME

    SERVICE-NAME は、サービスの名前に置き換えます。

    Cloud Run サービスは Google Cloud コンソールで削除することもできます。

  2. チュートリアルの設定時に追加した gcloud のデフォルトのリージョン構成を削除します。

     gcloud config unset run/region
    
  3. プロジェクト構成を削除します。

     gcloud config unset project