5分钟入门Google ADK -- 从零构建你的第一个AI Agent

Google ADK就像AI时代的智能管家,这篇教程带领大家快速构建自己的AI助手:零基础也能三步走!1️⃣安装配置Google ADK环境;2️⃣编写带工具的AI Agent;3️⃣启动Web界面体验对话交互以及友好型调试。五分钟实现功能完整的AI Agent,让编程小白也能轻松玩转Google ADK:)

什么是 Google ADK

Google ADK (Agent Development Kit) 是Google推出的AI代理开发工具包,让开发者能够快速构建功能强大的AI Agent。

今天我们用五分钟时间,带你从零开始构建第一个具备工具调用能力的AI Agent。即使你是编程新手也完全没问题,因为在AI时代最重要的是会与AI对话,技术细节AI都帮你处理好了:)

学完这篇文章,你将具备以下能力:

  • 熟练安装和配置Google ADK开发环境
  • 掌握编写带自定义工具的AI Agent
  • 学会使用Web界面进行Agent调试和交互

1. 环境准备与ADK安装

参考资料:Google ADK 官方快速入门

这里强调一下查阅官方文档的重要性。很多开发者习惯看二手资料,但往往信息滞后或不够准确。养成直接阅读官方一手资料的习惯,不仅能获得最新最准确的信息,还能培养独立解决问题的能力

虚拟环境配置(强烈推荐)

bash 复制代码
# 创建专用虚拟环境
python -m venv .venv

# 激活虚拟环境
# macOS/Linux:
source .venv/bin/activate
# Windows CMD:
# .venv\Scripts\activate.bat
# Windows PowerShell:
# .venv\Scripts\Activate.ps1

Google ADK安装

bash 复制代码
pip install google-adk

2. Agent项目构建

项目结构

根据官方规范,我们需要构建如下项目架构:

bash 复制代码
parent_folder/
    multi_tool_agent/
        __init__.py
        agent.py
        .env

创建项目文件夹

bash 复制代码
mkdir multi_tool_agent/

创建 __init__.py

bash 复制代码
echo "from . import agent" > multi_tool_agent/__init__.py

创建完成后,__init__.py 内容如下:

multi_tool_agent/init.py

python 复制代码
from . import agent

核心Agent实现

bash 复制代码
touch multi_tool_agent/agent.py

将下方完整代码复制到 agent.py 文件:

multi_tool_agent/agent.py

python 复制代码
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-2.0-flash",
    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],
)

创建 .env 文件

bash 复制代码
touch multi_tool_agent/.env

3. 设置模型

你的 Agent 需要 LLM 服务来理解用户请求和生成响应,这需要身份验证凭据。

方式一:使用 Google AI Studio(推荐新手)

  1. 获取 API 密钥 :访问 Google AI Studio 获取 API 密钥

  2. 配置环境变量 :打开 multi_tool_agent/.env 文件,复制粘贴以下代码:

multi_tool_agent/.env

bash 复制代码
GOOGLE_GENAI_USE_VERTEXAI=FALSE
GOOGLE_API_KEY=PASTE_YOUR_ACTUAL_API_KEY_HERE
  1. 替换API密钥 :将 PASTE_YOUR_ACTUAL_API_KEY_HERE 替换为你的实际 API 密钥

方式二:使用 Google Cloud Vertex AI

  1. 设置 Google Cloud

  2. 配置环境变量 :打开 multi_tool_agent/.env 文件:

multi_tool_agent/.env

bash 复制代码
GOOGLE_GENAI_USE_VERTEXAI=TRUE
GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
GOOGLE_CLOUD_LOCATION=LOCATION

4. 运行你的 Agent

切换到Agent项目的上级目录:

bash 复制代码
parent_folder/      <-- 进入到这个目录
    multi_tool_agent/
        __init__.py
        agent.py
        .env

提供三种不同的交互方式:

交互方式1:可视化Web界面(推荐)

启动可视化开发环境:

bash 复制代码
adk web

操作步骤:

第一步: 浏览器访问显示的地址(一般是 http://localhost:8000http://127.0.0.1:8000

第二步: 页面左上角下拉菜单选择 "multi_tool_agent"

注意事项 :如果下拉菜单看不到目标agent,检查是否在 multi_tool_agent 的父级目录 执行了 adk web 命令

第三步: 使用页面文本框开始对话:

第四步: 点击左侧 Events 标签页,可以详细查看函数调用过程、参数传递和返回结果:

Events 页面还可以点击 Trace 按钮查看每个事件的追踪日志,包括函数调用延迟等性能指标:

交互方式2:命令行终端

直接在终端与Agent对话:

bash 复制代码
adk run multi_tool_agent

看到如下提示即为启动成功:

bash 复制代码
Running agent weather_time_agent, type exit to exit.
[user]: 

退出方式:Cmd/Ctrl+C

交互方式3:API服务接口

bash 复制代码
adk api_server

这种方式会创建本地FastAPI服务,方便在正式部署前进行cURL请求测试

查看详细文档进行测试

💡 实战测试用例

参考官方推荐,可以尝试以下测试场景:

  • What is the weather in New York?
  • What is the time in New York?
  • What is the weather in Paris?
  • What is the time in Paris?

体验AI Agent功能

文本对话测试

在Web界面测试各种场景:

天气查询测试:

vbnet 复制代码
用户:What is the weather in New York?
Agent:🌤️ The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit).

时间查询测试:

sql 复制代码
用户:What is the time in New York?
Agent:🕐 The current time in New York is 2024-06-04 21:30:15 EST-0500

异常情况测试:

csharp 复制代码
用户:What is the weather in Paris?
Agent:❌ Weather information for 'Paris' is not available.

🎉 成就解锁!

恭喜你顺利完成了Google ADK入门之旅👍,现在可以给自己点个赞🎊!

你已经掌握了:

  • ✅ Google ADK环境的完整搭建流程
  • ✅ 带工具调用功能的AI Agent开发技巧
  • ✅ 多种Agent交互界面的使用方法
相关推荐
搞笑的秀儿35 分钟前
信息新技术
大数据·人工智能·物联网·云计算·区块链
阿里云大数据AI技术1 小时前
OpenSearch 视频 RAG 实践
数据库·人工智能·llm
XMAIPC_Robot1 小时前
基于ARM+FPGA的光栅尺精密位移加速度测试解决方案
arm开发·人工智能·fpga开发·自动化·边缘计算
加油吧zkf1 小时前
YOLO目标检测数据集类别:分类与应用
人工智能·计算机视觉·目标跟踪
Blossom.1182 小时前
机器学习在智能制造业中的应用:质量检测与设备故障预测
人工智能·深度学习·神经网络·机器学习·机器人·tensorflow·sklearn
天天扭码2 小时前
AI时代,前端如何处理大模型返回的多模态数据?
前端·人工智能·面试
难受啊马飞2.02 小时前
如何判断 AI 将优先自动化哪些任务?
运维·人工智能·ai·语言模型·程序员·大模型·大模型学习
顺丰同城前端技术团队2 小时前
掌握未来:构建专属领域的大模型与私有知识库——从部署到微调的全面指南
人工智能·deepseek
许泽宇的技术分享2 小时前
用.NET9+Blazor+Semantic Kernel,打造企业级AI知识库和智能体平台——AntSK深度解读
人工智能
烟锁池塘柳02 小时前
【深度学习】强化学习(Reinforcement Learning, RL)主流架构解析
人工智能·深度学习·机器学习