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

1. 概览

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

学习内容

  • 如何安装和设置 agents-cli 及其关联的技能。
  • 如何搭建新的代理项目。
  • ADK 2.0 图工作流代理项目的结构和关键文件。
  • 如何运行自动化 Linting 和代码清理。
  • 如何启动和使用本地 Web Playground 进行交互式测试(支持自动重新加载)。

所需条件

  • 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:声明性节点,用于定义由 LLM 提供支持的任务,其中包含特定指令、模型和结构化输出 (output_schema)。
  • 节点和上下文:使用 @node 修饰的 Python 函数(或标准函数),用于执行逻辑、通过 Context 访问执行状态,并生成 Event 对象以沿图传递数据和路由信号。
  • 模型:`gemini-3.1-flash-lite' 用作默认的快速推理模型。
  • 应用封装容器:顶层 App 对象封装根工作流。本地 Playground、ADK 评估框架和 Agent Runtime 等外部工具通过此标准化的 app 接口发现并执行您的工作流。

6. 自动 Linting

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

👉 提示 Antigravity:

Run linting on my agent project to verify its health.

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

7. 使用 Playground 进行互动式测试

本地 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?

测试实时自动重新加载

您可以查看对代理进行的实时编辑如何在 Playground 中反映出来。

  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. 在 Playground 中向智能体发送新消息,以测试自动重新加载功能:
    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 CLI 和 ADK 2.0 管理了 AI 智能体的端到端本地开发生命周期。

要点回顾

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

后续步骤

现在,您已经掌握了本地开发循环,接下来可以按以下步骤扩展智能体并将其投入生产环境:

  • 评估:使用 agents-cli eval run 针对评估集为智能体评分,以衡量准确率并发现回归。
  • 企业级云规模:部署和可观测性:使用 agents-cli deploy 将智能体打包并部署到 Agent Runtime 或 Cloud Run 等生产环境中。设置生产遥测,以将日志和执行轨迹流式传输到 Cloud Trace 和 BigQuery。

其他资源