氛围编程 AI 智能体:使用 Agents CLI 和 ADK 2.0 管理智能体生命周期

1. 概览

在此 Codelab 中,您将学习如何使用 Agents CLI 来管理 AI 智能体的完整本地开发生命周期。无论您是封装现有的 Gemini 模型,还是使用智能体开发套件 (ADK 2.0) 从头开始构建自定义智能体,Agents CLI 都能提供在本地搭建、构建、检查和测试智能体的工具。

学习内容

  • 如何安装和设置 agents-cli 及其相关技能。
  • 如何搭建新的智能体项目。
  • ADK 2.0 图形工作流智能体项目的结构和关键文件。
  • 如何运行自动检查和代码清理。
  • 如何启动和使用本地 Web 平台进行交互式测试,并自动重新加载。

所需条件

  • Python 3.11 或更高版本
  • uv 软件包管理器
  • Node.js 18+(如果使用编码智能体技能)
  • Antigravity IDE(从 Google Antigravity 安装和配置)

前提条件

此 Codelab 假定您熟悉以下内容:

  • 使用终端和命令行。

无需拥有 AI 智能体或 ADK 2.0 相关经验!

2. 设置身份验证和环境

提供身份验证凭据,以便智能体调用 Gemini 模型。

选项 1:Gemini API 密钥 (Google AI Studio)

如果您使用的是标准 Gemini API 密钥(您可以从 Google AI Studio 获取),请在 IDE 终端会话中导出该密钥:

export GEMINI_API_KEY="your_api_key_here"
export GOOGLE_GENAI_USE_ENTERPRISE=FALSE

选项 2:Google Cloud 应用默认凭证

如果您在 Google Cloud 上使用 Vertex AI,请使用 Google Cloud 应用默认凭据 (ADC) 进行身份验证,并设置活跃的 Google Cloud 项目:

gcloud auth application-default login
gcloud config set project <YOUR_PROJECT_ID>
export GOOGLE_GENAI_USE_ENTERPRISE=TRUE
export GOOGLE_CLOUD_PROJECT=REPLACE-WITH-YOUR-PROJECT_ID # Replace with your project ID
export GOOGLE_CLOUD_LOCATION=REPLACE-WITH-LOCATION # Replace the location

3. 设置 Agents CLI 和技能

第一步是安装 agents-cli 工具。此工具可处理智能体项目管理中的繁重工作。

安装 Antigravity 后,直接在终端中运行设置命令。

👉 打开终端并运行

uvx google-agents-cli setup

此命令会自动安装:

  1. 系统中的 Agents CLI 工具。
  2. 七项特定于领域的编码助理技能 ,Antigravity 可以使用这些技能来帮助您构建、搭建、评估和部署智能体。这些技能在 ~/.agents/skills/ 中全局安装一次,Antigravity 会自动发现它们。

注意:技能安装在 ~/.agents/skills/ 中,Antigravity 会自动获取它们。您可以使用 /skills 命令或 Antigravity 设置来验证这一点。

预期输出(已截断)

█▀█ █▀▀ █▀▀ █▄  ▀█▀ █▀ █▀▀  █`
`█▀█ █▄█ ██▄  ▀█  ▄█ █▄▄ █▄ █`

`Your coding agent just got an upgrade.`

`1. Authentication`

`─────────────────`

`✓ Authenticated with Google Cloud`

`2. CLI Installation`

`───────────────────`

`▸ uv tool install google-agents-cli`

`✓ Installed google-agents-cli`

`3. Skills Installation`

`──────────────────────`

`▸ npx -y skills add https://github.com/google/agents-cli -y --all -g`

`◇ Found 7 skills`

`~/.agents/skills/google-agents-cli-adk-code`

`~/.agents/skills/google-agents-cli-deploy`

`~/.agents/skills/google-agents-cli-eval`

`~/.agents/skills/google-agents-cli-observability`

`~/.agents/skills/google-agents-cli-publish`

`~/.agents/skills/google-agents-cli-scaffold`

`~/.agents/skills/google-agents-cli-workflow`

4. 创建智能体项目

在本部分中,您将使用原型模板创建一个结构完整的项目目录。

👉 提示 Antigravity:

Use ADK 2.0 to create a new graph workflow agent project called
customer-support-agent. I don't want to deploy this agent, so you can skip
the deployment files. The workflow should act as a customer support
representative for a shipping company. It should first classify if the user
query is related to shipping (rates, tracking, delivery, returns) or
unrelated. If it is related to shipping, route to a shipping FAQ agent to
answer the question. If it is unrelated, route to a node that politely
declines to answer.

Antigravity 会自动运行搭建命令 (agents-cli scaffold create customer-support-agent --prototype --yes) 并为您设置项目文件。

5. 探索智能体代码

👉 要求 Antigravity 解释生成的代码:

Read and explain the project structure of my new agent project. Walk me
through how `app/agent.py` is configured, highlighting the role of the
tools, nodes, edges, and the root Workflow.

在 Antigravity IDE 中,新创建的项目文件和工件直接显示在辅助窗格(左侧)中。您可以在其中查看 app/agent.py,也可以从 IDE 文件资源管理器中打开它,以探索搭建的代码。

# app/agent.py

from __future__ import annotations

from typing import Any, Literal

from google.adk.agents.context import Context
from google.adk.apps.app import App
from google.adk.events.event import Event
from google.adk.workflow import Edge
from google.adk.workflow import Workflow
from google.adk.workflow.agents.llm_agent import LlmAgent
from google.adk.workflow.node import node
from pydantic import BaseModel
from pydantic import Field


class InquiryCategory(BaseModel):
  category: Literal['shipping', 'unrelated'] = Field(
      description=(
          'Determine if the user query is related to shipping (rates, tracking,'
          ' delivery times, returns) or unrelated.'
      )
  )


def save_query(node_input: str):
  """Saves user query in state for downstream nodes."""
  yield Event(data=node_input, state={'user_query': node_input})


categorize_agent = LlmAgent(
    name='categorize',
    model='gemini-3.1-flash-lite',
    instruction='You are an expert classifier. Categorize the user query.',
    output_key='inquiry_category',
    output_schema=InquiryCategory,
)


@node
def route_inquiry(ctx: Context, node_input: Any):
  """Routes the workflow based on the classified category."""
  category_data = ctx.state.get('inquiry_category', {})
  category = category_data.get('category', 'unrelated')
  query = ctx.state.get('user_query', '')
  yield Event(data=query, route=category)


faq_agent = LlmAgent(
    name='shipping_faq',
    model='gemini-3.1-flash-lite'',
    instruction="""You are a customer support representative for a shipping company. Answer user questions based ONLY on the shipping FAQ below. Do not answer questions outside of the FAQ.
    
    SHIPPING FAQ:
    - Rates: Standard shipping is $5.99. Express shipping is $12.99. Orders
      over $50 qualify for free standard shipping.
    - Tracking: You can track your order by entering your tracking number on
      our website's tracking page.
    - Delivery Times: Standard delivery takes 3-5 business days. Express
      delivery takes 1-2 business days.
    - Returns: We offer free returns within 30 days of delivery. Please make
      sure the item is in its original condition.
    """,
)


@node
def handle_unrelated(ctx: Context, node_input: Any):
  """Handles unrelated inquiries politely."""
  yield Event(
      data=(
          'I am sorry, I am a shipping customer support assistant and can only'
          ' answer questions related to our shipping FAQ.'
      )
  )


root_agent = Workflow(
    name='customer_support_workflow',
    edges=[
        *Edge.chain('START', save_query, categorize_agent, route_inquiry),
        (route_inquiry, faq_agent, 'shipping'),
        (route_inquiry, handle_unrelated, 'unrelated'),
    ],
)

app = App(
    name='customer_support_agent',
    root_agent=root_agent,
)

关键概念

  • 工作流和边 :在 ADK 2.0 中,智能体应用使用 Workflow 作为图形进行编排。edges 列表定义了执行流程,将节点从 START 链接在一起,并根据路由启用条件分支(例如,在 "shipping" 上路由到 faq_agent 或在 "unrelated" 上路由到 handle_unrelated)。
  • LlmAgent:声明性节点,用于定义具有特定说明、模型和结构化输出 (output_schema) 的 LLM 驱动型任务。
  • 节点和上下文 :使用 @node 装饰的 Python 函数(或标准函数),用于执行逻辑、通过 Context 访问执行状态,并生成 Event 对象以沿图形传递数据和路由信号。
  • 模型:`gemini-3.1-flash-lite' 用作默认的快速推理模型。
  • 应用封装容器:顶级 App 对象封装了根工作流。本地平台、ADK 评估工具和智能体运行时等外部工具通过此标准化 app 接口发现并执行您的工作流。

6. 自动检查

在运行或测试智能体之前,最好确保代码干净且格式正确。

👉 提示 Antigravity:

Run linting on my agent project to verify its health.

Antigravity 将在后台执行 agents-cli lint 以运行预配置的检查,验证导入、语法和格式在文件中的一致性。

7. 使用平台进行交互式测试

本地 Web 平台是验证智能体行为的最快方式。它提供了一个交互式聊天界面,您可以在其中与智能体聊天并实时检查工具执行情况。

👉 提示 Antigravity:

Launch the local development playground for my agent.

Antigravity 将启动本地开发服务器 (agents-cli playground)。在 Web 浏览器中打开提供的网址(通常为 http://127.0.0.1:8080/dev-ui/?app=app),从下拉菜单中选择文件夹 app 以开始与智能体聊天。

在 Web 界面中开始与智能体聊天。尝试提出与配送相关的问题:

How much is standard shipping?

请注意,工作流如何成功分类并路由到 faq_agent 以回答问题。另请尝试提出不相关的问题,以验证工作流是否路由到 handle_unrelated 并正确拒绝回答:

What is the weather like?

测试实时自动重新加载

您可以了解对智能体的实时修改如何在平台中反映出来。

  1. 通过要求 Antigravity 执行以下操作,修改 app/agent.py 中的 faq_agent 指令:
    Modify the faq_agent instruction in app/agent.py to make the shipping rates
    response more playful and enthusiastic. Add some emojis and highlight the
    free shipping threshold.
    
  2. 在平台中向智能体发送新消息,以测试自动重新加载:
    How much is standard shipping?
    
    平台会自动重新加载并实时执行更新后的代码,而无需重启服务器!您现在应该会在响应中看到一些表情符号。

8. 命令行执行

如需进行快速测试、自动化或编写脚本,您可以要求 Antigravity 直接从终端运行智能体。

👉 提示 Antigravity:

Run a CLI query asking my agent how long standard delivery takes.

Antigravity 将执行查询命令 (agents-cli run "How long does standard delivery take?")。这会运行快速的单轮推理,并输出智能体的最终响应以及工具执行详情。

9. 清理

为避免在本地环境中留下不需要的资源,请按照以下清理步骤操作:

  1. 停止本地服务器:如果您的 agents-cli playground 服务器仍在运行,请在终端中按 Ctrl + C 将其停止。
  2. 移除本地项目文件:从本地机器中删除搭建的智能体项目目录。
rm -rf customer-support-agent

10. 总结与后续步骤

恭喜!您已成功使用 Agents CLIADK 2.0 管理了 AI 智能体的端到端本地开发生命周期。

要点回顾

  • 设置工具:安装了 Agents CLI 并为 Antigravity 配置了特定于领域的工作流技能。
  • 搭建了项目:使用标准化模板创建了结构完整的 customer-support-agent 项目。
  • 分析了 ADK 2.0 结构:探索了图形工作流、LLM 智能体、节点、边和条件路由。
  • 管理了本地健康状况:使用 agents-cli lint 运行了自动代码质量检查。
  • 验证了行为:通过平台使用实时热重载以交互方式测试了智能体,并在命令行中运行了快速测试。

后续步骤

现在您已掌握本地开发循环,接下来介绍如何扩展智能体并将其投入生产环境:

  • 评估:使用 agents-cli eval run 根据评估集对智能体进行评分,以衡量准确率并查找回归。
  • 企业级云规模:部署可观测性:使用 agents-cli deploy 将智能体打包并部署到生产环境(例如 Agent RuntimeCloud Run)。设置生产遥测,以将日志和执行轨迹流式传输到 Cloud Trace 和 BigQuery。

其他资源