Build and deploy an AI agent to Cloud Run using the Agent Development Kit (ADK)

The Agent Development Kit (ADK) framework simplifies the creation, evaluation, and deployment of AI agents. ADK provides a modular, code-first approach to building agents that can reason, plan, and utilize tools.

This tutorial shows you how to build and deploy an AI agent to Cloud Run using ADK for Python. This agent retrieves the weather report for a city you specify.

For more information about hosting your ADK agent using the Google Cloud CLI, see Deploy to Cloud Run in ADK documentation.

Objectives

Costs

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator.

New Google Cloud users might be eligible for a free trial.

Before you begin

  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, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  7. Set up your Cloud Run development environment in your Google Cloud project.
  8. Install ADK by following the instructions in the Agent Development Kit documentation.
  9. If you are under a domain restriction organization policy restricting unauthenticated invocations for your project, you will need to access your deployed service as described under Testing private services.

Required roles

To get the permissions that you need to deploy an AI agent to Cloud Run, ask your administrator to grant you the following IAM roles:

For more information about granting roles, see Manage access to projects, folders, and organizations.

You might also be able to get the required permissions through custom roles or other predefined roles.

To ensure that the service account attached to your Cloud Run service has the necessary permissions to call Gemini models from your deployed Cloud Run service, ask your administrator to grant the Agent Platform User (roles/aiplatform.user) IAM role to the service account attached to your Cloud Run service on your project.

For more information about granting roles, see Manage access to projects, folders, and organizations.

Your administrator might also be able to give the service account attached to your Cloud Run service the required permissions through custom roles or other predefined roles.

Write the sample application

To write an application in Python:

  1. Create a parent directory named weather-agent and change directory into it:

    mkdir weather-agent
    cd weather-agent
    
  2. In the weather-agent directory, create a subdirectory named multi_tool_agent and change directory into it:

    mkdir multi_tool_agent
    cd multi_tool_agent
    
  3. Create an __init__.py file to import the agent:

    from . import agent
    
  4. Create an agent.py file to define the agent for answering questions about the time and weather in a specified city:

    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-4-hydrogen",
        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. Create a .env file and add the following variables:

    GOOGLE_GENAI_USE_VERTEXAI=TRUE
    GOOGLE_CLOUD_PROJECT=PROJECT_ID
    GOOGLE_CLOUD_LOCATION=global
    

    Replace PROJECT_ID with your Google Cloud project ID.

  6. Navigate to the parent folder directory weather-agent, and create a requirements.txt file to add the google-adk dependency:

    google-adk
    

    Your source project includes the following structure:

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

Your app is finished and ready to be deployed.

Deploy to Cloud Run from source

Deploy from source automatically builds a container image from source code and deploys it.

  1. In your source code directory (weather-agent), deploy to Cloud Run using the following command:

    gcloud run deploy --source .
    1. When you are prompted for the service name, press Enter to accept the default name, for example weather-agent.

    2. If you are prompted to enable additional APIs on the project, for example, the Artifact Registry API, respond by pressing y.

    3. When you are prompted for region: select the region of your choice, for example europe-west1.

    4. If you are prompted to create a repository in the specified region, respond by pressing y.

    5. If you are prompted to allow public access: respond y. You might not see this prompt if there is a domain restriction organization policy that prevents it; for more details see the Before you begin section.

    Wait a few moments until the deployment completes. On success, the command line displays the service URL of the deployed agent in the following format: https://weather-agent-123456789101.us-central1.run.app.

Run your agent

To use the ADK agent, you can run the following curl commands:

  1. To get the list of apps, run the following command:

    curl -X GET SERVICE_URL/list-apps
    

    Replace SERVICE_URL with the URL of your deployed service.

  2. To start a session, run the following command:

    curl -X POST SERVICE_URL/apps/multi_tool_agent/users/u_123/sessions/s_123 -H "Content-Type: application/json" -d '{"key1": "value1", "key2": "value2"}'
    
  3. To query the agent, run the following command:

    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?\" }]}}"
    

The agent returns the weather information in the results of your query.

For more information and examples about the supported curl commands, see Use the API Server in ADK documentation.

Enable the ADK web UI

By default, the Python buildpack starts the ADK API server (adk api_server), which exposes only the REST endpoints. To test your agent interactively in a browser during development, you can override the buildpack entrypoint to start the ADK web UI (adk web) instead.

  1. From the weather-agent directory, redeploy the service with authentication required and GOOGLE_ENTRYPOINT set to adk web:

    gcloud run deploy --source . \
        --no-allow-unauthenticated \
        --set-build-env-vars='GOOGLE_ENTRYPOINT=adk web --port 8080 --host 0.0.0.0'
    

    When prompted, accept the default service name (weather-agent) and the same region you used earlier.

  2. Start an authenticated proxy to your service:

    gcloud run services proxy weather-agent --region=REGION

    Replace REGION with the region where you deployed the service.

  3. Open http://localhost:8080 in your browser.

    The service redirects to /dev-ui/ and loads the ADK web UI with multi_tool_agent selected.

  4. In the message input field, enter a prompt such as What's the weather in New York today? and click Send.

    The UI displays the get_weather tool call, tool response, and final answer from the agent.

  5. When you finish testing, remove the GOOGLE_ENTRYPOINT build environment variable to restore the default adk api_server entrypoint:

    gcloud run deploy --source . \
        --remove-build-env-vars=GOOGLE_ENTRYPOINT
    

Clean up

To avoid additional charges to your Google Cloud account, delete all the resources you deployed with this tutorial.

Delete the project

If you created a new project for this tutorial, delete the project. If you used an existing project and need to keep it without the changes you added in this tutorial, delete resources that you created for the tutorial.

The easiest way to eliminate billing is to delete the project that you created for the tutorial.

To delete the project:

  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.

Delete tutorial resources

  1. Delete the Cloud Run service you deployed in this tutorial. Cloud Run services don't incur costs until they receive requests.

    To delete your Cloud Run service, run the following command:

    gcloud run services delete SERVICE-NAME

    Replace SERVICE-NAME with the name of your service.

    You can also delete Cloud Run services from the Google Cloud console.

  2. Remove the gcloud default region configuration you added during tutorial setup:

     gcloud config unset run/region
    
  3. Remove the project configuration:

     gcloud config unset project