Building agents with ADK
Define an ADK LlmAgent with a model, an instruction and function tools, compose it with sub-agents or an AgentTool, and put deterministic checks in callbacks.
Chapter 4Custom agentsLesson 2 of 8ShowHide
Chapter 4 of 7 in Google Cloud Professional Agentic Architect
- Building agents with ADKYou're here
Prerequisites: The agent loop
Where does each behaviour live?
Your online store wants a support agent. It must look up orders, hand returns to a specialist, refuse returns over $100 without a person, and never show a full account number. In the agent loop lesson you traced a request through model calls and tool calls; now you build that agent. Google's is an open-source framework for agents in code (Python, TypeScript, Go, Java and Kotlin; the examples here are Python), and it is the base of the custom-agent work in this path.
Building one takes a few lines. The design question is where each behaviour belongs:
- The instruction for goals, tone and when to use what. The model reads it, so it guides; it does not enforce.
- A tool for anything that reads live data or changes a system.
- Another agent for a specialist job, attached either as a sub-agent (it takes over the conversation) or as an (the parent calls it like a function and gets its answer back).
- A , a function ADK runs at a fixed point in the loop, for checks and edits that must happen every time, because callbacks are your code, not the model's judgement.
Before you open a part, guess which one would guarantee that a reply never shows a full account number. Then click each part of the agent to see its field, an example and when it runs.
Build a support agent in five steps
Define the agent
An (aliased
Agent) needs aname. In practice you also give it amodel, aninstructionand adescription; the description is what other agents read when deciding whether to route work to it. The agent ADK starts from is the root agent; an app has one, and ADK's tools look for it under the nameroot_agent.from google.adk.agents import LlmAgent root_agent = LlmAgent( name="support_agent", model="gemini-flash-latest", description="Answers order questions for the online store.", instruction=( "You help customers with their orders. Use get_order_status when the " "user gives an order id. If you cannot help, say so plainly." ), )Add a function tool
Pass a plain Python function in
tools, and ADK wraps it as a function tool. It builds the declaration the model sees from the function's name, docstring, parameters and type hints, so give the function a descriptive name and write the docstring for the model, as in the agent loop lesson. Return a dictionary with astatuskey, which the ADK docs recommend so the model can tell success from failure.def get_order_status(order_id: str) -> dict: """Returns the status and tracking id of one customer order. Use when the user gives an order id. Not for policy questions. Args: order_id: The order id, for example "A1234". """ if order_id == "A1234": return {"status": "success", "order_status": "shipped", "tracking_id": "T-889"} return {"status": "error", "error_message": f"No order {order_id}."} root_agent = LlmAgent( ..., # name, model, description and instruction as in step 1 tools=[get_order_status], )ADK also offers built-in tools, such as Google Search and code execution, which are Gemini API features run by the Gemini service rather than your code. Some of them (Code Execution, Google Search, and Agent Search, Google's managed enterprise search from the RAG lesson) can only be used on their own in one agent, and built-in tools cannot be used inside a sub-agent. The documented workaround is to give each one its own agent and attach that agent to the main one as an AgentTool, not a sub-agent (see "Sub-agent or AgentTool" below). ADK Python can also lift the limit for the two search tools with
bypass_multi_tools_limit=True.Add a specialist agent
Returns are handled by a separate specialist. Give it its own instruction and a specific description, then list it in
sub_agents. ADK gives the parent a way to transfer control (transfer_to_agent), and the parent's model decides when, from the sub-agent descriptions.def start_return(order_id: str, reason: str, amount: float) -> dict: """Starts a return for a delivered order. Args: order_id: The order id, for example "A1234". reason: Why the customer is returning it, in their words. amount: The refund amount in US dollars. """ return {"status": "success", "return_id": "R-501"} returns_agent = LlmAgent( name="returns_agent", model="gemini-flash-latest", description="Handles return and refund requests for delivered orders.", instruction="Collect the order id, the reason and the refund amount, then start the return.", tools=[start_return], ) root_agent = LlmAgent( ..., # as in step 1 tools=[get_order_status], sub_agents=[returns_agent], )Block a disallowed argument with a callback
Returns over $100 need a person. Put that rule in a before-tool callback. It runs after the model proposes the call and before the tool executes; returning a dictionary skips the tool and sends that dictionary back as the result, while returning
Nonelets the tool run.from typing import Any, Optional from google.adk.tools.base_tool import BaseTool from google.adk.tools.tool_context import ToolContext def limit_returns(tool: BaseTool, args: dict[str, Any], tool_context: ToolContext) -> Optional[dict]: if tool.name == "start_return" and args.get("amount", 0) > 100: return {"status": "error", "error_message": "Returns over $100 need a person. Offer a handoff."} return None # let the tool run returns_agent = LlmAgent( ..., # as in step 3 tools=[start_return], before_tool_callback=limit_returns, )Run it with adk web
Install ADK (
pip install google-adk), put the code inagent.pyinside an agent folder with an__init__.pyand a.envfile holding your model credentials (a Gemini API key, or your Google Cloud project and location), then runadk webfrom the folder above it. The browser UI lets you chat with the agent and inspect each event: model calls, tool calls, transfers and the effect of any callback that changed a result.adk webcreates aRunnerfor you; in your own application code aRunneris the object that drives the loop for an agent, as in the agent loop lesson's snippet. The ADK Python quickstart walks through the setup.adk web --port 8000
Sub-agent or AgentTool: who keeps control?
Both attach one agent to another. The difference is control.
- A sub-agent receives control. When the parent's model transfers to it, the sub-agent answers the user, and in ADK's default (chat) mode it keeps answering until control is transferred again. Use it when the specialist should own the conversation for a while, such as a returns flow.
- An wraps an agent so the parent calls it like a function. The wrapped agent's answer comes back to the parent, which stays in charge and, by default, writes the reply. Use it when the parent needs a result to fold into its own work, such as a conversion or a lookup that needs reasoning.
from google.adk.tools.agent_tool import AgentTool
currency_agent = LlmAgent(
name="currency_agent",
model="gemini-flash-latest",
description="Converts an amount between currencies at today's rate.",
instruction="Convert the amount you are given and return only the result.",
tools=[get_exchange_rate],
)
travel_agent = LlmAgent(..., tools=[AgentTool(agent=currency_agent)])Each choice has a cost. An AgentTool keeps the parent in the middle of every exchange: one more model call to read the specialist's answer and relay it. A sub-agent saves that, but the parent gives up the conversation until control comes back.
A coordinator transfers to a chat-mode sub-agent, which answers. The user then sends another message. Which agent handles it?
Callbacks: where deterministic checks live
A callback runs at one of three before/after pairs of points in an LlmAgent's loop (Python adds error callbacks for failed model and tool calls):
| Callback | Runs | Return a value to… |
|---|---|---|
before_agent_callback / after_agent_callback | Around the agent's whole run | Skip the agent (before), or add content after its output (after) |
before_model_callback / after_model_callback | Around each model call | Skip the model call and use your response (before), or replace the model's response (after) |
before_tool_callback / after_tool_callback | Around each tool call | Skip the tool and use your result (before), or replace the tool's result (after) |
Returning None lets the step proceed unchanged. In Python, only None does:
an empty dictionary from a before-tool callback counts as a result, and the tool
is skipped.
An after-model callback, for example, can mask 16-digit account numbers in each model response, whatever the model wrote:
import re
from google.adk.agents.callback_context import CallbackContext
from google.adk.models import LlmResponse
def mask_accounts(callback_context: CallbackContext, llm_response: LlmResponse):
if not (llm_response.content and llm_response.content.parts):
return None
for part in llm_response.content.parts:
if part.text:
part.text = re.sub(r"\b\d{12}(\d{4})\b", r"************\1", part.text)
return llm_response # the masked response replaces the originalA real masker must match every format your numbers come in (spaces, dashes, other lengths), and with streaming responses it must handle numbers split across chunks, for example by masking the final text.
That makes callbacks the place for anything that must hold every time: argument checks, policy limits, masking data in a response, caching, logging. The instruction can say the same thing, and it is worth saying there so the model behaves well, but only the callback guarantees it.
Sources
Show 8 sourcesHide sources
| Source | Publisher | What it supports |
|---|---|---|
| Simple agents with LlmAgent (opens in a new tab) | Google, Agent Development Kit documentation | name, description, model, instruction, tools |
| Function tools (opens in a new tab) | Google, Agent Development Kit documentation | schema from name, docstring, parameters and type hints; Agent-as-a-Tool and its key difference from sub-agents |
| Custom tools (opens in a new tab) | Google, Agent Development Kit documentation | defining effective tool functions; the status key |
| "Custom agents", section "LLM delegation and agent transfer" (opens in a new tab) | Google, Agent Development Kit documentation | transfer_to_agent; distinct descriptions |
| Build collaborative agent teams (opens in a new tab) | Google, Agent Development Kit documentation | chat, task and single_turn modes, ADK 2.0 |
| "Callbacks" and "Types of callbacks" (opens in a new tab) | Google, Agent Development Kit documentation | return-value effects; only None lets the tool run in Python |
| Python quickstart (opens in a new tab) | Google, Agent Development Kit documentation | agent.py, root_agent, adk web |
| ADK: From basics to multi-tool agents (opens in a new tab) | Google Codelabs |
Suggested videos
Show 2 videosHide videos
Intro to multi-agent systems with ADK (opens YouTube in a new tab)
Current ADK walkthrough: an LlmAgent with model, instruction and tools, then composition with sub-agents.
Note: Doesn't go deep on AgentTool versus sub-agents.
Using Model Armor in ADK callbacks (opens YouTube in a new tab)
Uses ADK before and after callbacks for deterministic checks, which is the lesson's 'put deterministic checks in callbacks'.
Note: Shows callbacks only for Model Armor checks.
Review
How does control differ between a sub-agent and an AgentTool?
Check yourself
A refund tool must never run for amounts over $100. Where should that rule be enforced in an ADK agent?
Go deeper
Hands-on lab: Building AI Agents with ADK: Empowering with Tools →
Add a custom FunctionTool, built-in tools and third-party tools to an ADK agent. About 30 min. Codelab, runs in your own Google Cloud project with billing on.
LinkHands-on lab: Get Started with Agent Development Kit (ADK) →
ADK's core concepts and components, hands-on. About 1 h 30 min. Google Skills lab: sign-in and credits needed, temporary project provided.
LinkHands-on lab: Empower ADK agents with tools →
Prebuilt Google tools, LangChain and CrewAI tools, and your own functions. About 1 h 30 min. Google Skills lab: sign-in and credits needed, temporary project provided.