Back to Blog
Published:
Last Updated:
Fresh Content

Google ADK Tutorial: Build Your First AI Agent in 30 Minutes

10 min read
2,000 words
high priority
M

Muhammad Mudassir

Founder & CEO, Cognilium AI

Google ADK tutorial showing Vertex AI agent deployment workflow with code examples
Build and deploy your first AI agent on Google ADK with Gemini. Step-by-step tutorial with Python code—from setup to production in 30 minutes.
Google ADK agentVertex AI agentsGemini agent developmentGoogle Cloud AI agentsADK Python SDKreasoning engines Google

Google's Agent Development Kit (ADK) is the fastest way to deploy Gemini-powered agents to production. No infrastructure wrangling. No complex orchestration setup. In this tutorial, you'll go from zero to a deployed agent in 30 minutes—with code you can copy and modify.

What is Google ADK?

Google ADK (Agent Development Kit) is Google Cloud's framework for building and deploying AI agents on Vertex AI. It provides tools, templates, and deployment automation for creating Gemini-powered agents that can use tools, access external data, and run in production with enterprise-grade reliability.

What You'll Build

By the end of this tutorial, you'll have:

✅ A working AI agent powered by Gemini 1.5 Pro ✅ Custom tools the agent can call ✅ Deployed to Cloud Run (serverless, auto-scaling) ✅ Connected to Google Search for real-time grounding

Example agent: A research assistant that can search the web, perform calculations, and provide sourced answers.

Prerequisites

RequirementDetails
Google Cloud AccountWith billing enabled
gcloud CLIInstalled and authenticated
Python3.9 or higher
Vertex AI APIEnabled in your project

Time required: 30 minutes

Step 1: Google Cloud Setup

Create a New Project

# Create project
gcloud projects create my-adk-agent --name="ADK Agent Tutorial"

# Set as default
gcloud config set project my-adk-agent

# Enable billing (required)
# Do this in Cloud Console: https://console.cloud.google.com/billing

Enable Required APIs

gcloud services enable \
    aiplatform.googleapis.com \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com

Set Up Authentication

# Create service account
gcloud iam service-accounts create adk-agent-sa \
    --display-name="ADK Agent Service Account"

# Grant Vertex AI permissions
gcloud projects add-iam-policy-binding my-adk-agent \
    --member="serviceAccount:adk-agent-sa@my-adk-agent.iam.gserviceaccount.com" \
    --role="roles/aiplatform.user"

# Grant Cloud Run permissions
gcloud projects add-iam-policy-binding my-adk-agent \
    --member="serviceAccount:adk-agent-sa@my-adk-agent.iam.gserviceaccount.com" \
    --role="roles/run.invoker"

# Create and download key (for local development)
gcloud iam service-accounts keys create key.json \
    --iam-account=adk-agent-sa@my-adk-agent.iam.gserviceaccount.com

# Set environment variable
export GOOGLE_APPLICATION_CREDENTIALS="$(pwd)/key.json"

Step 2: Install ADK SDK

Create Project Directory

mkdir my-adk-agent
cd my-adk-agent

Set Up Virtual Environment

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

Install Dependencies

pip install google-cloud-aiplatform[reasoningengine,langchain]
pip install cloudpickle==3.0.0
pip install langchain==0.2.0

Verify Installation

import vertexai
from vertexai.preview import reasoning_engines

print("ADK SDK installed successfully!")
print(f"Vertex AI version: {vertexai.__version__}")

Step 3: Create Your Agent

Create a file agent.py:

import vertexai
from vertexai.preview import reasoning_engines

# Initialize Vertex AI
PROJECT_ID = "my-adk-agent"
LOCATION = "us-central1"

vertexai.init(project=PROJECT_ID, location=LOCATION)

# Define the agent
agent = reasoning_engines.LangchainAgent(
    model="gemini-1.5-pro",
    system_instruction="""You are a helpful research assistant. Your role is to:
    
    1. Answer questions accurately and thoroughly
    2. Use available tools when they would help
    3. Cite sources when providing factual information
    4. Acknowledge uncertainty when you're not sure
    
    Be concise but complete. Format responses for readability.""",
    
    model_kwargs={
        "temperature": 0.7,
        "max_output_tokens": 2048,
    }
)

Understanding the Code

ParameterPurpose
modelGemini model to use (1.5-pro recommended)
system_instructionSets agent behavior and personality
model_kwargsModel parameters like temperature

Step 4: Add Custom Tools

Tools let your agent take actions beyond generating text. Add tools to agent.py:

def calculate(expression: str) -> str:
    """
    Evaluate a mathematical expression.
    
    Args:
        expression: A math expression like "2 + 2" or "sqrt(16)"
    
    Returns:
        The calculation result as a string
    """
    import math
    
    # Safe evaluation with math functions
    allowed = {k: v for k, v in math.__dict__.items() if not k.startswith("_")}
    allowed.update({"abs": abs, "round": round, "pow": pow})
    
    try:
        result = eval(expression, {"__builtins__": {}}, allowed)
        return f"Result: {result}"
    except Exception as e:
        return f"Error calculating: {str(e)}"


def get_current_time(timezone: str = "UTC") -> str:
    """
    Get the current time in a specified timezone.
    
    Args:
        timezone: Timezone name like "UTC", "US/Pacific", "Europe/London"
    
    Returns:
        Current time in the specified timezone
    """
    from datetime import datetime
    import pytz
    
    try:
        tz = pytz.timezone(timezone)
        current_time = datetime.now(tz)
        return f"Current time in {timezone}: {current_time.strftime('%Y-%m-%d %H:%M:%S %Z')}"
    except Exception as e:
        return f"Error getting time: {str(e)}"


def search_knowledge_base(query: str) -> str:
    """
    Search an internal knowledge base for information.
    
    Args:
        query: Search query string
    
    Returns:
        Relevant information from knowledge base
    """
    # Placeholder - in production, connect to Vertex AI Search or your database
    knowledge = {
        "pricing": "Our pricing starts at $99/month for the starter plan.",
        "support": "Support is available 24/7 via chat or email.",
        "features": "Key features include: AI agents, analytics, and integrations.",
    }
    
    query_lower = query.lower()
    for key, value in knowledge.items():
        if key in query_lower:
            return value
    
    return "No specific information found. Please rephrase your query."


# Update agent with tools
agent = reasoning_engines.LangchainAgent(
    model="gemini-1.5-pro",
    system_instruction="""You are a helpful research assistant with access to tools.
    
    Available tools:
    - calculate: For math calculations
    - get_current_time: For current time in any timezone
    - search_knowledge_base: For company-specific information
    
    Use tools when they would provide better answers than your training data.""",
    
    tools=[calculate, get_current_time, search_knowledge_base],
    
    model_kwargs={
        "temperature": 0.7,
        "max_output_tokens": 2048,
    }
)

Tool Design Best Practices

  1. Clear docstrings: Gemini uses docstrings to understand when to call tools
  2. Type hints: Help the model understand expected inputs
  3. Error handling: Always return meaningful error messages
  4. Single responsibility: One tool = one action

Step 5: Test Locally

Create test_agent.py:

from agent import agent

# Test basic query
response = agent.query(input="What is the square root of 256?")
print("Math test:", response)

# Test time tool
response = agent.query(input="What time is it in Tokyo?")
print("Time test:", response)

# Test knowledge base
response = agent.query(input="What are your pricing options?")
print("Knowledge test:", response)

# Test multi-turn conversation
response = agent.query(input="My name is Alex. I'm interested in your product.")
print("Intro:", response)

response = agent.query(input="What features would be most useful for a startup?")
print("Follow-up:", response)

Run tests:

python test_agent.py

Expected output:

Math test: The square root of 256 is 16.
Time test: Current time in Asia/Tokyo: 2025-01-15 09:23:45 JST
Knowledge test: Our pricing starts at $99/month for the starter plan.
...

Step 6: Deploy to Cloud Run

Create Deployment Script

Create deploy.py:

import vertexai
from vertexai.preview import reasoning_engines
from agent import agent

# Initialize Vertex AI
PROJECT_ID = "my-adk-agent"
LOCATION = "us-central1"

vertexai.init(project=PROJECT_ID, location=LOCATION)

# Deploy as Reasoning Engine
remote_agent = reasoning_engines.ReasoningEngine.create(
    agent,
    requirements=[
        "google-cloud-aiplatform[reasoningengine,langchain]",
        "cloudpickle==3.0.0",
        "langchain==0.2.0",
        "pytz",  # For timezone tool
    ],
    display_name="research-assistant-agent",
    description="AI research assistant with calculation and time tools",
)

print(f"Agent deployed!")
print(f"Resource name: {remote_agent.resource_name}")

Run deployment:

python deploy.py

This takes 3-5 minutes. You'll see:

Agent deployed!
Resource name: projects/123456/locations/us-central1/reasoningEngines/789012

Query Deployed Agent

# Get deployed agent
from vertexai.preview import reasoning_engines

remote_agent = reasoning_engines.ReasoningEngine(
    "projects/123456/locations/us-central1/reasoningEngines/789012"
)

# Query it
response = remote_agent.query(input="Calculate 15% tip on a $47.50 bill")
print(response)

Step 7: Add Google Search Grounding

ADK's killer feature: real-time web grounding. Update your agent:

from vertexai.preview.generative_models import grounding

# Create agent with Google Search grounding
agent_with_grounding = reasoning_engines.LangchainAgent(
    model="gemini-1.5-pro",
    system_instruction="""You are a research assistant with access to real-time web search.
    
    When answering questions about current events, news, or rapidly changing information,
    use web search to get the latest data. Always cite your sources.""",
    
    tools=[
        grounding.GoogleSearchRetrieval(),  # Built-in web search
        calculate,
        get_current_time,
    ],
    
    model_kwargs={
        "temperature": 0.7,
        "max_output_tokens": 2048,
    }
)

Test Grounded Responses

response = agent_with_grounding.query(
    input="What are the latest developments in AI agents this week?"
)
print(response)
# Agent searches the web and cites sources

What You've Built

Congratulations! You now have:

ComponentStatus
Gemini-powered agent✅ Running
Custom tools (math, time, knowledge)✅ Working
Cloud Run deployment✅ Live
Google Search grounding✅ Enabled
Auto-scaling infrastructure✅ Configured

Estimated Costs

ResourceCost (10K queries/month)
Gemini 1.5 Pro~$200
Cloud Run~$30
Google Search API~$50
Total~$280/month

What's Next

Expand Your Agent

  1. Add Vertex AI Search → Ground your agent with enterprise knowledge bases

  2. Multi-Agent Orchestration → Build systems with multiple specialized agents

  3. Compare with AWS → Understand when to use AgentCore instead

Production Enhancements

  1. Add authentication via Cloud Identity
  2. Set up monitoring with Cloud Operations
  3. Implement rate limiting for production traffic
  4. Connect to BigQuery for analytics

Want help building production ADK agents?

At Cognilium, we've deployed AI agents across AWS and Google Cloud for enterprise clients. Whether you're choosing between platforms or scaling an existing deployment, we can help →

Share this article

Muhammad Mudassir

Muhammad Mudassir

Founder & CEO, Cognilium AI

Mudassir Marwat is the Founder & CEO of Cognilium AI, where he leads the design and deployment of pr...

Frequently Asked Questions

Find answers to common questions about the topics covered in this article.

Still have questions?

Get in touch with our team for personalized assistance.

Contact Us