Google ADK教程:快速构建AI智能体

本教程通过构建一个有状态回显代理,深入讲解Google Agent Development Kit (ADK) 的核心组件与工作流。你将学习如何配置Gemini模型、创建FunctionTool、使用SessionService管理状态,并通过Runner编排事件流。教程涵盖从环境搭建到代码逐行解析,并补充了常见错误排查与生产环境优化建议,帮助开发者快速掌握ADK的工程实践。

技术背景

随着大语言模型能力的增强,构建复杂AI代理(Agent)的需求日益增长。然而,直接调用模型API往往难以管理多步交互、状态持久化和工具调用。Google ADK(Agent Development Kit)应运而生,它提供了一套标准化的组件(Agent、Tool、Session、Runner)来简化代理开发,使开发者能够专注于业务逻辑而非底层编排。本教程通过一个简单的回显代理,展示ADK如何管理状态转换(START->PROCESSING->END),为理解更复杂的代理系统打下基础。

核心原理

ADK的核心是事件驱动架构。Runner负责执行代理,它接收用户输入,调用Agent的模型,模型根据指令决定是否调用工具,工具执行后返回结果,模型再生成最终响应。整个过程通过事件流(Event)暴露,开发者可以监听并处理这些事件。状态管理通过SessionService实现,每个会话(Session)维护一个状态字典,工具可以通过ToolContext访问和修改它。本示例中,代理通过FunctionTool修改workflow_status,演示了状态如何在工具调用间传递。

架构分析

本示例的架构包含四个核心组件:1) Agent(LlmAgent):配置了Gemini模型和指令,是决策中心;2) FunctionTool:包装Python函数,提供状态更新能力;3) InMemorySessionService:管理会话状态,支持创建和查询会话;4) Runner:编排执行流程,将用户消息传递给Agent,并处理工具调用循环。数据流为:用户输入->Runner->Agent->模型->工具调用->状态更新->模型生成响应->Runner返回事件。设计上,Agent通过指令明确工具调用时机,确保状态转换顺序。

完整实战教程

##### 版权所有 2026 Google LLC.

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

ADK 简单演示:使用 Gemini 的有状态 Echo Agent

本笔记本提供了一个使用 Google Agent Development Kit (ADK) 中 Gemini 的基础入门示例。

目标: 演示 ADK 如何编排一个简单的工作流,该工作流涉及围绕与 Gemini API 的核心交互进行状态转换(START -> PROCESSING -> END)。

场景:

你将构建一个“有状态回显代理”。该代理的主要任务是回显用户的输入。然而,它将使用 ADK 组件在整个过程中管理其内部状态:

  1. 它以 START 状态开始。
  2. 收到输入后,它使用 ADK 工具转换到 PROCESSING 状态。
  3. 它准备回显响应(隐式使用代理中配置的 Gemini 模型)。
  4. 它再次使用 ADK 工具转换到 END 状态。
  5. 它传递最终的回显响应。

此示例突出了 ADK 在管理结构化工作流和状态方面的作用,即使对于简单任务也是如此。

<!-- 社区贡献者徽章 -->

<table>

<tr>

<!-- 作者头像单元格 -->

<td bgcolor="#d7e6ff">

<a href="https://github.com/andycandy" target="_blank" title="在 GitHub 上查看 Anand Roy 的个人资料">

</a>

</td>

<!-- 文本内容单元格 -->

<td bgcolor="#d7e6ff">

<h2><font color='black'>本笔记本由 <a href="https://github.com/andycandy" target="_blank"><font color='#217bfe'><strong>Anand Roy</strong></font></a> 贡献。</font></h2>

<h5><font color='black'><a href="https://www.linkedin.com/in/anand-roy-61a2b529b"><font color="#078efb">LinkedIn</font></a> - 查看 <a href="https://github.com/andycandy" target="_blank"><font color="#078efb"><strong>Anand</strong></font></a> 的其他笔记本 <a href="https://github.com/search?q=repo%3Agoogle-gemini%2Fcookbook%20%22Anand%20Roy%22&type=code" target="_blank"><font color="#078efb">此处</font></a>。</h5></font><br>

<!-- 页脚 -->

<font color='black'><small><em>有很酷的 Gemini 示例?欢迎 <a href="https://github.com/google-gemini/cookbook/blob/main/CONTRIBUTING.md" target="_blank"><font color="#078efb">也分享出来</font></a>!</em></small></font>

</td>

</tr>

</table>

设置

%pip install -q google-adk google-genai python-dotenv

1. 配置 Google API 密钥

为了让 Agent 使用 Gemini,需要访问 Google Generative AI API。下一个代码单元将配置你的 API 密钥。

重要提示: 本示例使用 Colab Secrets(userdata.get('GEMINI_API_KEY'))。请确保你已在 Colab Secrets 管理器(查看 -> 密钥)中存储了名为 GEMINI_API_KEY 的密钥。

from google.colab import userdata
import os
from dotenv import load_dotenv

api_key = userdata.get('GEMINI_API_KEY')
os.environ['GEMINI_API_KEY'] = api_key
load_dotenv()

2. 本演示中的核心 ADK 组件

此示例使用以下关键 ADK 组件:

* Agent:由 Gemini 模型驱动的智能体。它理解指令、决定何时使用工具并生成响应。

* FunctionTool:提供给智能体的自定义能力。在本例中,它是一个用于更新工作流状态的工具。

* ToolContext:自动传递给我们的工具的对象,允许其访问和修改 会话状态。

* SessionService (InMemorySessionService):管理对话的状态(workflow_status)。InMemory 表示状态仅在此脚本运行期间存在。

* Runner:编排整个交互:将用户输入传递给智能体,处理工具调用,通过 SessionService 管理状态,并交付最终响应。

* 会话状态:一个字典,保存当前对话(会话)的数据。在这里,您使用它来存储 {'workflow_status': '...'}。

from google.adk.agents import Agent
from google.adk.tools import FunctionTool, ToolContext
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.sessions import Session

3. 定义 ADK 组件(工具、代理、服务)

现在,让我们为有状态回显代理定义核心 ADK 组件:

  1. 工具(set_workflow_state): 一个 Python 函数,包装为 ADK FunctionTool。当代理调用此函数时,它将修改会话状态中的 workflow_status。
  2. 代理(echo_agent): 一个 LlmAgent,配置了 Gemini 模型、关于*何时*调用 state_tool 的具体指令以及工具本身。
  3. 服务(session_service、runner): InMemorySessionService 用于保存状态,Runner 用于执行代理。
  4. 会话: 用于创建具有初始状态 {'workflow_status': 'START'} 的特定会话实例。
async def set_workflow_state(state_name: str, tool_context: ToolContext) -> dict:
    """Sets the current workflow state in the session state.

    Use this tool to mark progress through the workflow stages:
    - Call with 'PROCESSING' before handling the user input.
    - Call with 'END' after handling the user input.

    Args:
        state_name: The state to set (e.g., 'PROCESSING', 'END').
        tool_context: Injected context to access session state.

    Returns:
        A dictionary confirming the status update.
    """
    try:
        tool_context.state['workflow_status'] = state_name
        return {'status': 'success', 'message': f'Workflow state set to {state_name}'}
    except Exception as e:
        return {'status': 'error', 'message': f'Failed to set state: {e}'}

# Create the function tool
state_tool = FunctionTool(func=set_workflow_state)
GEMINI_MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}
echo_agent = Agent(
  name="EchoAgent",
  description="An agent that echoes input while tracking workflow state.",
  model=GEMINI_MODEL_ID,
  instruction="""
    You are a simple echo agent. You also manage a workflow status stored in the session state under the key 'workflow_status'.
    The workflow states are: START, PROCESSING, END.

    Your Workflow:
    1. The workflow starts in the 'START' state (this is set externally).
    2. When you receive user input:
        a. FIRST, use the 'set_workflow_state' tool to change the status to 'PROCESSING'.
        b. THEN, simply repeat the user's exact input back to them in your response text.
        c. AFTER preparing the echo response text, use the 'set_workflow_state' tool AGAIN to change the status to 'END'.
        d. FINALLY, provide only the echo response text to the user.
  """,
  tools=[state_tool],
)
session_service = InMemorySessionService()
runner = Runner(
    agent=echo_agent,
    session_service=session_service,
    app_name="EchoAgentDemo"
)

APP_NAME="EchoAgentDemo"
USER_ID="1"
ID="session_01"

session = session_service.create_session(
    app_name=APP_NAME,
    user_id=USER_ID,
    session_id=ID,
    state={'workflow_status': 'START'}
)

4. 运行交互

现在,通过 Runner 向 echo_agent 发送一条简单消息("Hello ADK!")。Runner 将根据代理的指令管理执行流程。

预期流程:

  1. 代理接收 "Hello ADK!"。
  2. 代理调用 set_workflow_state 工具(状态 -> PROCESSING)。
  3. 代理调用 set_workflow_state 工具(状态 -> END)。
  4. 代理以文本 "Hello ADK!" 响应。

下一个单元格启动 run_async 调用,并处理执行期间生成的事件流,记录步骤。

from google.genai.types import Content, Part

user_input_text = "Hello ADK!"
user_message = Content(role='user', parts=[Part(text=user_input_text)])
final_agent_response_text = None
async def process_interaction_events():
    """Helper async function to process events."""
    global final_agent_response_text
    event_count = 0
    async for event in runner.run_async(session_id=ID, new_message=user_message, user_id=USER_ID):
        event_count += 1
        print(f"\n[Event {event_count}] Type: {type(event).__name__}")

        if event.content:
            part = event.content.parts[0]
            role = event.content.role
            print(f"  Role: {role}")
            if part.text:
                print(f"  Text: '{part.text}'")
                if role == 'model':
                    final_agent_response_text = part.text
            elif part.function_call:
                print(f"  >>> Function Call <<<")
                print(f"      Name: {part.function_call.name}")
                print(f"      Args: {part.function_call.args}")
            elif part.function_response:
                print(f"  <<< Function Response >>>")
                print(f"      Name: {part.function_response.name}")
                print(f"      Data: {part.function_response.response}")

await process_interaction_events()

5. 分析结果

检查上面打印的“Agent 事件日志”。你应该能清晰地看到反映智能体指令的序列:

  1. Function Call 事件,目标是 set_workflow_state,参数为 args={'state_name': 'PROCESSING'}。
  2. Function Response 事件,确认第一次工具执行。
  3. Function Call 事件,目标是 set_workflow_state,参数为 args={'state_name': 'END'}。
  4. Function Response 事件,确认第二次工具执行。
  5. 最终事件,包含智能体的文本响应(回显的消息)。

下一个单元格通过检查会话中存储的最终状态来验证这一结果。

final_session = session_service.get_session(
    session_id=session.id,
    user_id=USER_ID,
    app_name=APP_NAME
)

if final_session:
    final_state = final_session.state
    workflow_status = final_state.get('workflow_status')
    print(f"Final workflow status: {workflow_status}")

if final_agent_response_text:
    print(f"Agent response: {final_agent_response_text}")

后续步骤与深入学习

本笔记本演示了 ADK 应用的基本结构,包括:

* 定义一个由 Gemini 驱动的 Agent。

* 创建一个简单的 FunctionTool 来修改状态。

* 使用 SessionService 和 ToolContext 进行状态管理。

* 使用 Runner 编排流程。

要更深入地了解 Google Agent Development Kit 的功能:

  1. 探索官方文档: 有关所有组件(Agents、Tools、Sessions、Callbacks、Multi-Agent 系统等)的详细说明,请访问 Google ADK 文档站点。
  2. 尝试入门笔记本: 在 Colab 上探索 官方 ADK 教程笔记本,获得构建第一个 Agent 的动手实践介绍。
  3. 发现更多示例: 查看 Google ADK GitHub 仓库,获取更广泛的示例,包括更复杂的工作流、集成和高级 Agent 模式。

考虑探索以下概念:

* 工作流 Agents(SequentialAgent、ParallelAgent、LoopAgent)用于结构化流程控制。

* 多 Agent 系统 用于构建协作式 Agent 团队。

* 其他 工具类型(OpenAPI、Google Cloud Tools、内置工具)用于更广泛的集成。

常见问题

常见错误:1) API密钥未配置,导致认证失败,需检查环境变量GEMINI_API_KEY;2) 模型ID错误,需确认模型可用性;3) 工具函数签名错误,ToolContext参数必须存在;4) 会话状态未初始化,导致访问state时KeyError;5) 异步事件处理不当,需使用async for。排查方法:打印事件流,检查工具调用参数和响应;使用session_service.get_session验证状态。生产环境优化:使用持久化SessionService(如Redis)替代内存实现;增加错误重试机制;使用日志记录事件流;考虑使用多Agent架构分解复杂任务。

企业应用扩展

深入学习可探索:1) 工作流Agent(SequentialAgent、ParallelAgent、LoopAgent)实现结构化流程;2) 多Agent系统协作;3) 其他工具类型(OpenAPI、Google Cloud Tools);4) 回调机制(Callbacks)自定义行为;5) 集成外部API和数据库。官方文档和GitHub仓库提供了丰富示例,建议从ADK教程笔记本开始实践。

总结

本教程通过构建一个有状态回显代理,深入讲解Google Agent Development Kit (ADK) 的核心组件与工作流。你将学习如何配置Gemini模型、创建FunctionTool、使用SessionService管理状态,并通过Runner编排事件流。教程涵盖从环境搭建到代码逐行解析,并补充了常见错误排查与生产环境优化建议,帮助开发者快速掌握ADK的工程实践。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部AI 智能体教程