中文译本。原文见同目录 README.md

第 13 课:用 ADK 构建你的第一个 Agent

引言

你已经走过基础部分。你理解 Agent 是什么、如何思考、如何用工具、如何记忆,以及如何评估它们是否做得好。现在该动手构建一个了。

本课将带你用 Google 的 Agent Development Kit(ADK)构建一个实用 Agent。结束时,你会理解如何搭建项目、定义 Agent、赋予工具、本地测试,甚至构建一支协作的小型 Agent 团队。

我们会保持概念层面,并把精确代码示例链接到官方 quickstart——这样你总能拿到最新语法,我们则专注真正重要的想法。


我们要构建什么

目标是一个能做到这些事的实用 Agent:

  • 用 Google Search 回答某主题的问题
  • 调用你定义的自定义工具(如查天气或产品信息)
  • 在本地运行,便于快速测试与迭代

把它想成 Agent 的「hello world」——一坐下来就能理解,但足够真实,能展示各部分如何连在一起。

Interactive Agent Architecture Builder

Configure an agent by selecting components and see the architecture update live

🧠 Model Selection
🏗️ Agent Type
🔧 Tools
Est. Cost/Call
$0.001
Est. Latency
~1s
Capability
★★★
Architecture Diagram
Generated System Prompt

      

前置条件

开始前,请确保你有:

  • 已安装 Python 3.9+
  • 已安装 ADK(pip install google-adk)
  • 已启用 Gemini API 的 Google Cloud 项目
  • 已配置 API key 或 application default credentials

完成设置: 详细安装说明见官方指南 ADK Getting Started。


ELI5:我们实际上在做什么?

构建第一个 Agent 就像拼乐高套装。你有底板(项目结构)、小人脑(语言模型)、一些工具配件(搜索、自定义函数),以及说明书(system instructions)告诉小人该怎么表现。

每块以特定方式卡在一起。大脑决定做什么。工具让它能做事。说明让它保持专注。底板把一切固定住,不散架。

美妙之处在于:一旦理解零件如何配合,你就可以替换、增加或重新排列,搭出完全不同的东西。


分步演练

让我们走一遍构建第一个 Agent 的流程。每一步讲概念,精确代码指向官方 quickstart。

步骤 1:搭建项目结构

ADK 期望特定的项目布局。最简单时,你需要一个 Agent 文件夹,里面两个文件:

my_first_agent/
    __init__.py
    agent.py

文件夹名成为 Agent 的模块名。__init__.py 告诉 Python 这是一个包并导出你的 Agent。agent.py 是你定义 Agent 本身的地方。

这个结构很重要,因为 ADK 工具(如 adk web 与 adk eval)靠寻找这种模式来发现你的 Agent。从一开始就保持干净一致。

提示: 也可以用 adk create my_first_agent 自动脚手架生成该结构。

步骤 2:定义你的 Agent

每个 ADK Agent 至少需要三样东西:

  1. 名称(name) —— Agent 的唯一标识符
  2. 模型(model) —— 用于推理的 Gemini 模型
  3. 系统说明(system instructions) —— 告诉 Agent 它是谁、如何表现的提示词

概念上大致如下:

from google.adk.agents import Agent

my_agent = Agent(
    name="my_first_agent",
    model="gemini-3.5-flash",
    instruction="You are a helpful assistant that answers questions clearly and concisely.",
)

model 参数决定由哪个 Gemini 模型负责推理。学习与原型阶段,gemini-3.5-flash 是很好的选择——快、有能力、成本友好。更复杂的推理任务可升级到 gemini-3.1-pro。(也可以用滚动别名如 gemini-flash-latest,始终拿到最新 Flash 模型。)

instruction 参数是 Agent 的 system prompt。在这里定义个性、能力与边界。本课稍后会讲如何写好说明。

步骤 3:创建自定义 function tool

工具是 Agent 与聊天机器人的分野。让我们给 Agent 一个可调用的自定义函数。

ADK 中的 tool 就是一个带清晰 docstring 的 Python 函数。docstring 很重要,因为 ADK 用它告诉模型工具做什么、何时使用。

def get_weather(city: str) -> dict:
    """Get the current weather for a given city.

    Args:
        city: The name of the city to get weather for.

    Returns:
        A dictionary with weather information.
    """
    # In a real agent, this would call a weather API
    # For now, return mock data
    return {
        "city": city,
        "temperature": "72F",
        "conditions": "Sunny",
    }

注意这些关键点:

  • 类型提示(city: str、-> dict)帮助模型理解该传什么参数、期望什么返回
  • docstring 是模型了解工具用途的方式——写得像向同事解释函数
  • 函数名 应有描述性——模型用它决定何时调用该工具

然后把工具挂到 Agent 上:

my_agent = Agent(
    name="my_first_agent",
    model="gemini-3.5-flash",
    instruction="You are a helpful assistant. Use the get_weather tool when asked about weather.",
    tools=[get_weather],
)

步骤 4:添加内置工具(Google Search)

ADK 自带若干内置工具。最有用之一是 Google Search grounding,让 Agent 能搜索网络获取当前信息。

from google.adk.tools import google_search

my_agent = Agent(
    name="my_first_agent",
    model="gemini-3.5-flash",
    instruction="You are a helpful assistant. Use search for current events and get_weather for weather.",
    tools=[get_weather, google_search],
)

现在 Agent 既能搜网又能查天气。模型根据用户问题决定用哪个工具。问新闻就搜索。问天气就调用你的自定义函数。

步骤 5:本地运行与测试

ADK 包含本地开发服务器,提供与 Agent 交互的 Web UI:

adk web

这会启动本地服务器(通常在 http://localhost:8000),带聊天界面。你可以:

  • 向 Agent 发消息
  • 查看它调用了哪些工具以及原因
  • 检查完整对话历史
  • 实时调试问题

也可以从命令行测试:

adk run my_first_agent

这是最快的反馈环。改一处、刷新、测试。重复直到 Agent 按你想要的方式表现。

步骤 6:用 ADK eval 做评估

Agent 跑通后,你希望改动时它仍然可靠。ADK 为此包含评估框架:

adk eval my_first_agent eval_data.json

评估让你定义测试用例——输入与期望行为的配对——并自动检查 Agent 是否正确处理。这就是 Agent 版的单元测试。

评估概念在第 9 课已深入讲过。这里的关键是:即使是第一个 Agent,也尽早开始写 eval 用例。它能帮你避免以后的回归。

完整 quickstart: 完整代码见 ADK Quickstart


ADK 中的 Agent 类型

ADK 提供四种 Agent 类型,各自面向不同任务。选对类型就像选对数据结构——它塑造后续一切。

LlmAgent(默认)

这是你最常使用的类型。它用语言模型决定下一步做什么。

何时使用:

  • 任务需要推理与判断
  • Agent 需要根据上下文决定调用哪些工具
  • 用户交互是对话式的

工作方式: 模型收到用户消息、可用工具与对话历史。它决定是调用工具、问澄清问题,还是直接回答。这就是 ReAct 循环在起作用。

from google.adk.agents import Agent

researcher = Agent(
    name="researcher",
    model="gemini-3.5-flash",
    instruction="You research topics thoroughly using search.",
    tools=[google_search],
)

SequentialAgent(按顺序执行)

SequentialAgent 按固定列表依次运行子 Agent,像一条流水线。

何时使用:

  • 任务有清晰、有序的阶段
  • 每阶段依赖上一阶段输出
  • 你想要可预测、可重复的执行

示例: 内容创作流水线——一个 Agent 调研,下一个写草稿,第三个做语法与风格编辑。

from google.adk.agents import SequentialAgent

pipeline = SequentialAgent(
    name="content_pipeline",
    sub_agents=[researcher, writer, editor],
)

类比: 把 SequentialAgent 想成工厂装配线。每个工位做一件事,把结果传给下一站。

ParallelAgent(并行执行)

ParallelAgent 并发运行多个子 Agent 并汇总结果。

何时使用:

  • 有彼此独立、互不依赖的子任务
  • 速度重要,想缩短挂钟时间
  • 需要对同一输入的多种视角

示例: 同时跑安全审查、性能审查与风格审查来评估一段代码。

from google.adk.agents import ParallelAgent

review_team = ParallelAgent(
    name="code_review",
    sub_agents=[security_reviewer, perf_reviewer, style_reviewer],
)

类比: 把 ParallelAgent 想成团队头脑风暴——大家同时做各自的部分,再汇总发现。

LoopAgent(重复直到完成)

LoopAgent 循环运行其子 Agent,直到满足终止条件。

何时使用:

  • 任务需要迭代打磨
  • 你想持续改进输出直到达到质量阈值
  • 迭代次数事先未知

示例: 写作 Agent 起草内容、按标准评估、修订,直到质量分超过阈值。

from google.adk.agents import LoopAgent

refiner = LoopAgent(
    name="iterative_writer",
    sub_agents=[drafter, evaluator, reviser],
    max_iterations=5,
)

类比: 把 LoopAgent 想成代码评审循环——你写、收反馈、改,重复直到评审通过。

选择合适的 Agent 类型

Agent 类型 何时使用 示例
LlmAgent 需要灵活推理 Chatbot、研究助手
SequentialAgent 固定步骤流水线 ETL、内容创作
ParallelAgent 独立并行任务 多审查员系统
LoopAgent 迭代打磨 质量改进循环

你也可以组合这些类型。SequentialAgent 的某一步可以是 LlmAgent。LoopAgent 内部可以包含 ParallelAgent。这种可组合性是 ADK 的优势之一。

了解更多: ADK Agent Types


构建多工具 Agent

多数真实 Agent 需要不止一个工具。看看如何组合多种能力。

组合搜索、代码执行与自定义工具

from google.adk.agents import Agent
from google.adk.tools import google_search

def look_up_product(product_id: str) -> dict:
    """Look up product details by ID.

    Args:
        product_id: The unique product identifier.

    Returns:
        Product details including name, price, and availability.
    """
    # Call your product database/API here
    return {"id": product_id, "name": "Widget Pro", "price": 29.99}

def calculate_discount(price: float, discount_percent: float) -> float:
    """Calculate the discounted price.

    Args:
        price: The original price.
        discount_percent: The discount percentage (e.g., 20 for 20%).

    Returns:
        The price after discount.
    """
    return price * (1 - discount_percent / 100)

shopping_agent = Agent(
    name="shopping_assistant",
    model="gemini-3.5-flash",
    instruction="""You are a shopping assistant. You can:
    - Search the web for product reviews and comparisons
    - Look up specific products in our catalog by ID
    - Calculate discounts on prices

    Always look up the product first before calculating discounts.""",
    tools=[google_search, look_up_product, calculate_discount],
)

多工具 Agent 的关键是:对何时用哪个工具给出清晰说明。没有引导时,模型可能该查库时却去搜网,或反过来。

工具设计原则

为 Agent 构建工具时,遵循这些指南:

  1. 一个工具,一件事。 每个工具应做好一件事。不要造一个处理五种操作的超级工具。

  2. 描述性名称与 docstring。 模型根据名称与描述选工具。get_order_status 好过 fetch_data。

  3. 清晰的参数类型。 使用类型提示。模型需要知道该传字符串、数字还是对象。

  4. 优雅的错误处理。 返回有用的错误信息,而不是崩溃。模型若理解出了什么问题,往往能恢复。

  5. 尽可能确定性。 对相同输入返回一致结果的工具,更易于模型推理。


构建 Agent 团队

有时单个 Agent 处理不了一切。你可能需要专家——一个做研究,一个写作,一个事实核查。ADK 让你用根 Agent 委托给子 Agent 的方式构建团队。

根 Agent 模式

from google.adk.agents import Agent

# Specialist agents
researcher = Agent(
    name="researcher",
    model="gemini-3.5-flash",
    instruction="You research topics using web search. Return factual findings.",
    tools=[google_search],
)

writer = Agent(
    name="writer",
    model="gemini-3.5-flash",
    instruction="You write clear, engaging content based on research findings.",
)

fact_checker = Agent(
    name="fact_checker",
    model="gemini-3.5-flash",
    instruction="You verify claims by searching for supporting evidence.",
    tools=[google_search],
)

# Root agent that orchestrates
coordinator = Agent(
    name="content_team",
    model="gemini-3.1-pro",
    instruction="""You coordinate a content creation team. For any content request:
    1. Ask the researcher to gather information
    2. Ask the writer to create content based on the research
    3. Ask the fact_checker to verify key claims

    Delegate tasks to your team members and synthesize their work.""",
    sub_agents=[researcher, writer, fact_checker],
)

何时用子 Agent vs 多个工具

做法 最适合 取舍
一个 Agent,多个工具 单条推理链就能完成的任务 更简单,但工具太多时 Agent 可能困惑
多个子 Agent 受益于专精分工的任务 更灵活,但增加协调开销

经验法则: 若单个 Agent 有超过 10–15 个工具,并开始搞不清该用哪个,考虑拆成带聚焦工具集的子 Agent。

Agent 之间的通信

ADK 中的子 Agent 共享 session state,相当于共享工作区。根 Agent 可以把上下文传给子 Agent,子 Agent 可以存储其他 Agent 可访问的结果。

可以想成团队项目里的共享文档。协调者写 brief,研究者补充发现,写作者用这些发现起草内容。


写好系统说明的技巧

系统说明(prompt)是影响 Agent 行为的最重要单一因素。以下是实用指南。

角色要具体

弱:

You are a helpful assistant.

更好:

You are a customer support agent for Acme Corp. You help customers
with order tracking, returns, and product questions. You have access
to the order database and can look up orders by ID or email.

设定清晰边界

告诉 Agent 该做什么、不该做什么:

You ONLY handle questions about orders, returns, and products.
For billing questions, tell the customer to contact billing@acme.com.
Never make promises about delivery dates unless the tracking system confirms them.
Never share internal pricing or cost information.

提供示例

展示你希望它如何表现:

When a customer asks about their order status, follow this pattern:
1. Ask for their order ID if they have not provided one
2. Look up the order using the get_order tool
3. Summarize the status in plain language
4. If the order is delayed, apologize and offer to escalate

Example:
Customer: "Where is my order?"
You: "I'd be happy to help track your order. Could you share your order ID? It should start with ORD- and you can find it in your confirmation email."

定义输出格式

若要结构化响应,就说清楚:

Always respond in this format:
- Start with a one-sentence summary
- Provide details in bullet points
- End with a suggested next step

常见说明错误

错误 为什么有问题 修复
太含糊(「要有帮助」) 模型没有具体引导 定义角色、范围与行为
太长(2000+ 词) 关键说明淹没在噪音里 保持聚焦,用结构
无工具引导 模型猜测何时用工具 说明每个工具何时合适
无错误处理 Agent 不知道失败时怎么办 加入回退说明
无边界 Agent 试图包办一切 定义什么超出范围

初学者常见错误

1. 一开始就太复杂

第一天不需要带 10 个工具的多 Agent 系统。从一个 Agent、一个工具开始。跑通跑稳再加复杂度。

2. 忽视系统说明

许多初学者盯着工具与代码,却只写一行系统说明。说明是控制 Agent 行为的主要杠杆。在它上面投入时间。

3. 不测试工具调用

Agent 的可靠性取决于其工具。接入 Agent 前,先独立测试每个工具函数。若 get_weather("London") 抛异常,你的 Agent 也会。

4. 忘记处理错误

工具会失败。API 会超时。数据会缺失。Agent 需要说明:出问题时该怎么办。在工具代码与系统说明里都加上错误处理。

5. 用错模型

不是每个任务都需要最强模型。简单路由与工具调用,Flash 这类更轻的模型就很好,还能省钱。把更大模型留给真正需要复杂推理的任务。

6. 跳过评估

没有 eval 用例,你就不知道改动是改进还是破坏。开始迭代 prompt 前,至少写 5–10 个测试用例。

7. 把密钥写进代码

永远不要在 Agent 代码里硬编码 API key 或凭证。用环境变量或 secrets manager。这是标准软件工程实践,但做原型时很容易忘。


汇总在一起

构建 ADK Agent 的全过程可以这样理解:

1. Define the goal
   "What should this agent accomplish?"
        |
        v
2. Choose the agent type
   LlmAgent? Sequential? Parallel? Loop?
        |
        v
3. Write the system instruction
   Role, scope, boundaries, examples
        |
        v
4. Define the tools
   What actions does the agent need?
        |
        v
5. Wire it together
   Agent + model + instruction + tools
        |
        v
6. Test locally
   adk web / adk run
        |
        v
7. Write eval cases
   Input -> expected behavior
        |
        v
8. Iterate
   Improve instructions, add tools, refine
        |
        v
9. Deploy
   Agent Engine or your own infrastructure

每一步喂给下一步。而步骤 6–8 是一个循环——你会转多圈,再进入步骤 9。


速查:ADK CLI 命令

命令 作用
pip install google-adk 安装 ADK
adk create <name> 脚手架新建 Agent 项目
adk web 启动带 Web UI 的本地开发服务器
adk run <agent> 从命令行运行 Agent
adk eval <agent> <data> 对 Agent 跑评估用例
adk deploy agent_engine 部署 Agent 到 Agent Engine

去哪里深入学习


关键要点

  1. ADK Agent 需要三样东西: 名称、模型与系统说明。工具是可选的,但正是工具让 Agent 真正有用。

  2. 从 LlmAgent 起步。 它覆盖多数用例。只有有清晰结构理由时,再上 SequentialAgent、ParallelAgent 或 LoopAgent。

  3. 系统说明是主要控制杠杆。 角色要具体,设边界,给示例,并包含错误处理引导。

  4. 尽早、经常测试。 用 adk web 做交互测试,用 adk eval 做自动化回归检查。

  5. 增量构建。 一个 Agent、一个工具、一个 eval 用例。每块跑通再加下一块。


接下来做什么?

现在你会构建 Agent 了,还需要理解 Agent 如何与更广阔的世界通信。下一课我们将探索两个重要协议——MCP 与 A2A——它们让 Agent 用开放标准与工具、以及彼此对话。

下一课:Lesson 14 - Agent Protocols: MCP and A2A -->