1. 概览
学习内容
在此 Codelab 中,您将使用 Agents CLI 和智能体开发套件 (ADK) 构建、测试和部署可用于生产环境的 AI 智能体。您将在不到一小时的时间内完成从安装工具到在 Google Cloud 的代理运行时上运行实时代理的整个过程。
构建内容
客户服务 AI 智能体,可以:
- 使用自然语言回答问题
- 调用自定义工具(天气和时间查询)
- 在本地接受测试,并获得即时反馈
- 自动接受质量评估
- 在 Google Cloud 上以生产模式运行
使用 Agents CLI 的两种方式
Agents CLI 支持两种工作流:
🤖 使用代码智能体(推荐初学者使用)
让 AI 为您指路!将技能安装到 Gemini CLI、Antigravity、Claude Code、Cursor 或任何其他受支持的编码智能体中,它们将帮助您逐步构建智能体。
👤 手动模式(适合喜欢直接控制的开发者)
自行从终端运行命令。您将输入每个命令,并确切了解会发生什么。
在此 Codelab 中,我们将展示这两种方法。选择适合您风格的!
所需条件
必需:
- Python 3.11 或更高版本
- uv 软件包管理器
- Node.js 18 及更高版本(用于编码代理技能)
- 启用了结算功能的 Google Cloud 项目
- Google Cloud SDK 已安装
仅限本地开发时可选:
- AI Studio API 密钥(用于本地测试,可替代 GCP)
前提条件
本 Codelab 假定您熟悉以下内容:
- 使用终端/命令行
- 基本 Python 概念
- Google Cloud 控制台基础知识
无需具备 AI 智能体或 ADK 相关经验!
2. 准备工作
设置 Google Cloud
创建或选择项目
- 前往 Google Cloud 控制台
- 创建新项目或选择现有项目
- 记下您的项目 ID,稍后您会用到该信息
启用必需的 API
在终端中运行以下命令(或使用 Cloud 控制台):
gcloud services enable aiplatform.googleapis.com \
run.googleapis.com \
cloudtrace.googleapis.com \
cloudbuild.googleapis.com
这样,您就可以:
- Agent Platform - 适用于 Gemini 模型和 Agent Runtime
- Cloud Run - 替代部署选项
- Cloud Trace - 可观测性和监控
- Cloud Build - 构建自动化
身份验证
gcloud auth login
gcloud auth application-default login
设置环境变量
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
export GOOGLE_CLOUD_LOCATION=us-central1
将 YOUR_PROJECT_ID 替换为您的实际项目 ID。
3. 安装 Agents CLI
🤖 使用编码代理
如果您使用的是 Gemini CLI、Antigravity、Claude Code、Cursor 或任何其他受支持的编码智能体:
uvx google-agents-cli setup
此命令会安装:
- Agents CLI 工具(全局)
- 7 项技能,您机器上任何受支持的编码代理都可以使用这些技能来帮助您构建代理(技能只需安装一次,每个支持这些技能的代理都可以发现它们)
预期输出(已剪裁):
█▀█ █▀▀ █▀▀ █▄ █ ▀█▀ █▀ █▀▀ █ █ █▀█ █▄█ ██▄ █ ▀█ █ ▄█ █▄▄ █▄ █ 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
技能通过 skills (npx -y skills@latest) 安装到 ~/.agents/skills/ 中,并由您机器上的每个受支持的编码代理自动拾取。
👤 手动模式
如果您希望直接运行命令,请执行以下操作:
uv tool install google-agents-cli
验证安装:
agents-cli --version
预期输出:
agents-cli, version 0.1.2
4. 创建代理项目
🤖 使用编码代理
向编码智能体提出以下问题:
“使用原型模板创建一个名为 customer-support-agent 的新 ADK 代理项目”
代理会运行脚手架命令并为您创建项目。
👤 手动模式
使用快速模式创建与此 Codelab 一致的项目:
agents-cli scaffold create customer-support-agent --prototype --yes
这样一来,系统会立即创建一个基本的 ADK 代理项目,其中包含本 Codelab 所需的所有代码。
预期输出:
Agents CLI v0.1.2 > Verifying GCP credentials... > ✓ Connected to project: YOUR_PROJECT_ID ✅ Success! Your agent project is ready. 📖 Documentation README: cat customer-support-agent/README.md 💡 Tip Add a deployment target later with: agents-cli scaffold enhance 🚀 Get Started cd customer-support-agent && agents-cli install && agents-cli playground
替代方案:互动模式
如果您想探索其他代理类型,请在不使用标志的情况下运行:
agents-cli scaffold create customer-support-agent
您会看到以下选项:
- adk - 简单的 ReAct 智能体(请为 Codelab 选择此项)
- adk_a2a - 智能体间通信
- agentic_rag - 基于 RAG 的文档问答
创建了什么?
customer-support-agent/
├── app/
│ ├── agent.py # Your agent code (main file)
│ ├── fast_api_app.py # Development server (replaced when you add a deployment target)
│ └── app_utils/ # Utilities (telemetry, etc.)
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── eval/ # Evalsets and rubric config for `adk eval`
├── Dockerfile # Container image (removed when you switch to Agent Runtime)
├── GEMINI.md # Coding-agent context for this project
├── pyproject.toml # Project config & dependencies
├── README.md # Project documentation
└── .gitignore
5. 探索代理代码
前往您的项目
cd customer-support-agent
检查代理
打开 app/agent.py - 这是定义代理的位置:
import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.models import Gemini
from google.genai import types
import os
import google.auth
_, project_id = google.auth.default()
os.environ["GOOGLE_CLOUD_PROJECT"] = project_id
os.environ["GOOGLE_CLOUD_LOCATION"] = "global"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
def get_weather(query: str) -> str:
"""Simulates a web search. Use it get information on weather.
Args:
query: A string containing the location to get weather information for.
Returns:
A string with the simulated weather information for the queried location.
"""
if "sf" in query.lower() or "san francisco" in query.lower():
return "It's 60 degrees and foggy."
return "It's 90 degrees and sunny."
def get_current_time(query: str) -> str:
"""Simulates getting the current time for a city.
Args:
city: The name of the city to get the current time for.
Returns:
A string with the current time information.
"""
if "sf" in query.lower() or "san francisco" in query.lower():
tz_identifier = "America/Los_Angeles"
else:
return f"Sorry, I don't have timezone information for query: {query}."
tz = ZoneInfo(tz_identifier)
now = datetime.datetime.now(tz)
return f"The current time for query {query} is {now.strftime('%Y-%m-%d %H:%M:%S %Z%z')}"
root_agent = Agent(
name="root_agent",
model=Gemini(
model="gemini-flash-latest",
retry_options=types.HttpRetryOptions(attempts=3),
),
instruction="You are a helpful AI assistant designed to provide accurate and useful information.",
tools=[get_weather, get_current_time],
)
app = App(
root_agent=root_agent,
name="app",
)
主要概念
工具:智能体可以调用的 Python 函数
get_weather(query)- 返回模拟天气(旧金山为雾天,气温 60°F;其他地区为晴天,气温 90°F)get_current_time(query)- 返回当前时间(在此桩中仅限旧金山)
模型:gemini-flash-latest 是一个别名,可自动跟踪最新的稳定版 Gemini Flash,因此即使 Google 发布新版本,此代码也能继续正常运行。如需固定特定模型,请换用 gemini-2.5-flash(稳定版)或 gemini-3-flash-preview(预览版)之类的模型。
应用 / root_agent:ADK 项目会公开一个封装 root_agent 的顶级 App。平台、adk eval 和 Agent Runtime 都会通过此 app 对象发现代理。
位置 =
"global":部分 Gemini 预览版模型仅通过 global 端点提供,因此脚手架会明确设置该端点。
指令:用于塑造代理行为的系统提示。
6. 使用 Playground 在本地进行测试
游乐场提供了一个交互式聊天界面,可用于测试。
🤖 使用编码代理
向代理提出问题:
“为我的代理启动 Playground”
👤 手动模式
先安装依赖项
agents-cli install
此命令会在后台运行 uv sync,将代理的依赖项解析并安装到本地 .venv 中。
启动 Playground
agents-cli playground
预期输出:
╭──────────────────────────────────────────────────────────────────────────────╮ │ Starting your agent playground... │ │ │ │ Will be available at: http://127.0.0.1:8080/dev-ui/?app=app │ ╰──────────────────────────────────────────────────────────────────────────────╯ ▸ uv run adk web . --host 127.0.0.1 --port 8080 --reload_agents INFO: Started server process INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8080
试试看
- 在浏览器中打开 http://127.0.0.1:8080/dev-ui/?app=app
- 不妨试试这些提示:
- “旧金山的天气如何?”
- “东京的天气如何?”
- “旧金山现在是几点?”
观看智能体如何:
- 调用
get_weather工具 - 调用
get_current_time工具 - 将结果整合为自然的回答
7. 从命令行运行
在不打开浏览器的情况下测试智能体。
🤖 使用编码代理
向代理提出问题:
“运行智能体,查询‘巴黎的天气如何?’”
👤 手动模式
agents-cli run "What's the weather in San Francisco?"
预期输出:
Using project root directory: /path/to/customer-support-agent
Local server started on port 18080 (PID 30008)
Stop with: agents-cli run --stop-server
[user]: What's the weather in San Francisco?
[root_agent]:
[tool_call: get_weather({"query": "San Francisco"})]
[tool_response: get_weather -> {"result": "It's 60 degrees and foggy."}]The weather in San Francisco is 60 degrees and foggy.
Session: fb30f7f7-147e-4697-8aaa-706d604589fa (resume with --session-id)
在后台,run 会启动一个后台 adk api_server(保持预热状态约 30 分钟),以便后续调用快速完成。使用 agents-cli run --stop-server 显式停止。继续与 --session-id 进行多轮对话。
run 命令非常适合用于以下情况:
- 开发期间的快速测试
- 脚本和自动化
- CI/CD 流水线
8. 评估智能体
ADK 评估会验证两项独立的事项:
- 工具轨迹 - 智能体是否使用正确的实参调用了正确的工具?确定性完全匹配。
- 回答质量 - 最终回答是否相关、有帮助且基于工具输出?由充当评估者的 LLM 进行评分。
您需要同时具备这两种权限。仅根据评分准则进行评分可能会通过看起来不错的虚假回答;仅根据轨迹无法判断用户是否获得了有用的回复。Codelab evalset 同时练习了这两种方法。
这些是由两个文件驱动的:
tests/eval/evalsets/basic.evalset.json- 要重放的对话,以及预期的工具调用tests/eval/eval_config.json- 要评分的指标、这些指标的阈值以及 LLM 评判员的评分标准
修改评估集以纳入预期工具调用
将 tests/eval/evalsets/basic.evalset.json 的内容替换为:
{
"eval_set_id": "basic_eval",
"name": "Basic Agent Evaluation",
"description": "Validates that the agent calls the right tools AND produces a quality response.",
"eval_cases": [
{
"eval_id": "weather_san_francisco",
"conversation": [
{
"user_content": {"parts": [{"text": "What's the weather like in San Francisco?"}], "role": "user"},
"final_response": {"parts": [{"text": "The weather in San Francisco is 60 degrees and foggy."}], "role": "model"},
"intermediate_data": {
"tool_uses": [{"name": "get_weather", "args": {"query": "San Francisco"}}],
"tool_responses": [],
"intermediate_responses": []
}
}
],
"session_input": {"app_name": "app", "user_id": "eval_user", "state": {}}
},
{
"eval_id": "weather_tokyo",
"conversation": [
{
"user_content": {"parts": [{"text": "What's the weather in Tokyo?"}], "role": "user"},
"final_response": {"parts": [{"text": "The weather in Tokyo is 90 degrees and sunny."}], "role": "model"},
"intermediate_data": {
"tool_uses": [{"name": "get_weather", "args": {"query": "Tokyo"}}],
"tool_responses": [],
"intermediate_responses": []
}
}
],
"session_input": {"app_name": "app", "user_id": "eval_user", "state": {}}
},
{
"eval_id": "time_san_francisco",
"conversation": [
{
"user_content": {"parts": [{"text": "What time is it in San Francisco?"}], "role": "user"},
"intermediate_data": {
"tool_uses": [{"name": "get_current_time", "args": {"query": "San Francisco"}}],
"tool_responses": [],
"intermediate_responses": []
}
}
],
"session_input": {"app_name": "app", "user_id": "eval_user", "state": {}}
}
]
}
intermediate_data.tool_uses 代码块是预期轨迹,即代理应调用哪些工具以及使用哪些实参。轨迹指标会将此与运行时实际发生的情况进行比较。
修改评分准则以对这两个指标进行评分
将 tests/eval/eval_config.json 替换为:
{
"criteria": {
"tool_trajectory_avg_score": 1.0,
"rubric_based_final_response_quality_v1": {
"threshold": 0.8,
"judgeModelOptions": {"judgeModel": "gemini-flash-latest", "numSamples": 1},
"rubrics": [
{"rubricId": "relevance", "rubricContent": {"textProperty": "The response directly addresses the user's query."}},
{"rubricId": "helpfulness", "rubricContent": {"textProperty": "The response is helpful and provides useful information."}},
{"rubricId": "tool_grounded", "rubricContent": {"textProperty": "The response is grounded in the values returned by the tools (e.g. the exact temperature and weather condition) and does not invent details."}}
]
}
}
}
各行的作用:
tool_trajectory_avg_score: 1.0- 添加了轨迹指标,并将严格阈值设置为 1.0(每个预期工具调用都必须完全匹配)。通过将代理的实际function_call事件与intermediate_data.tool_uses进行比较,以确定方式计算得分。rubric_based_final_response_quality_v1- 运行 LLM-as-judge(此处为gemini-flash-latest),该模型会根据每条评分准则对最终回答进行评分(范围为 0 到 1),然后计算平均分。当平均值达到threshold(0.8) 时,测试通过。tool_grounded评分标准明确要求评审员惩罚与工具输出相矛盾或编造工具输出的答案,这是在轨迹检查的基础上增加的一层防范幻觉的措施。
🤖 使用编码代理
向代理提出问题:
“为我的代理运行评估”
👤 手动模式
agents-cli eval run --all
--all 在 tests/eval/evalsets/ 下每 *.evalset.json 运行一次。如需定位到其中一个,请使用 --evalset tests/eval/evalsets/basic.evalset.json。
预期输出(已剪裁):
▸ uv run adk eval ./app tests/eval/evalsets/basic.evalset.json --config_file_path tests/eval/eval_config.json
INFO - google_llm.py - Sending out request, model: gemini-flash-latest, backend: GoogleLLMVariant.VERTEX_AI
INFO - local_eval_set_results_manager.py - Writing eval result to file: app/.adk/eval_history/app_basic_eval_<ts>.evalset_result.json
Using evaluation criteria: criteria={'tool_trajectory_avg_score': 1.0, 'rubric_based_final_response_quality_v1': BaseCriterion(threshold=0.8, ...)}
*********************************************************************
Eval Run Summary
basic_eval:
Tests passed: 3
Tests failed: 0
每个测试用例的结果都写入 app/.adk/eval_history/ 下,每个结果文件都会列出每个指标的分数,以便您准确了解哪些检查通过或未通过。
如何读取结果文件
app/.adk/eval_history/app_basic_eval_ 中的通过测试用例如下所示:
{
"eval_id": "weather_san_francisco",
"final_eval_status": 1,
"overall_eval_metric_results": [
{"metric_name": "tool_trajectory_avg_score", "score": 1.0, "threshold": 1.0, "eval_status": 1},
{"metric_name": "rubric_based_final_response_quality_v1","score": 1.0, "threshold": 0.8, "eval_status": 1}
]
}
如果代理出现幻觉并调用了错误的工具(或未调用任何工具),tool_trajectory_avg_score 会降至 0.0,并且测试用例会失败,即使最终文本看起来合理也是如此。这是仅靠评分标准无法提供的属性。
其他可用指标
ADK 随附了多个内置评估器,您可以将其添加到 criteria:
指标 | 检查内容 |
| 与预期轨迹完全匹配的工具调用 |
| LLM 根据评分标准进行评估(最终回答) |
| 根据评分标准评估 LLM(工具使用) |
| LLM 评判:最终回答在语义上是否与预期回答等效? |
| 实际最终回答与预期最终回答之间的 ROUGE-1 |
| LLM 评判器:回答的安全性 |
| LLM 判断:回答基于提供的上下文 |
9. 添加 Agent Runtime 部署
Agent Runtime 是 Google Cloud 针对 ADK 代理提供的托管式无服务器运行时。它会自动处理扩缩、基础设施和可观测性。
🤖 使用编码代理
向代理提出问题:
“向我的项目添加 Agent Runtime 部署”
👤 手动模式
agents-cli scaffold enhance --deployment-target agent_runtime --yes
预期输出:
Agents CLI v0.1.2 Resolved project root to: /home/user/customer-support-agent Generating templates for comparison... - Original template... - Enhanced template... Comparing files... Will auto-update (unchanged by you): ✓ README.md ✓ app/app_utils/telemetry.py Skipping (your code): - app/agent.py Files to add: + app/agent_runtime_app.py + deployment_metadata.json + tests/integration/test_agent_runtime_app.py Files to remove: - Dockerfile - app/fast_api_app.py - tests/integration/test_server_e2e.py Dependency changes: + Add: google-cloud-aiplatform[evaluation,agent-engines]>=1.130.0 + Add: protobuf>=6.31.1,<7.0.0 📦 Creating backup before modification... Backup created: /home/user/.agents-cli/backups/customer-support-agent_20260430_001940 Updated: 2 files Added: 3 files Removed: 3 files ✅ Enhance complete!
有何变化?
添加时间:
app/agent_runtime_app.py- Agent Runtime 封装容器deployment_metadata.json- 部署跟踪- Agent Runtime 专用测试
已移除:
Dockerfile- 不需要(Agent Runtime 由系统管理)fast_api_app.py- 已替换为 Agent Runtime 应用
Preserved:
app/agent.py- 您的代理代码(未做任何更改!)
10. 部署到 Agent Runtime
将代理部署到 Google Cloud 的托管式基础架构。
更新依赖项
uv lock
🤖 使用编码代理
向代理提出问题:
“将我的代理部署到项目 YOUR_PROJECT_ID、区域 us-central1 中的 Agent Runtime”
👤 手动模式
agents-cli deploy --project YOUR_PROJECT_ID --region us-central1
预期输出:
Using project root directory: /home/user/customer-support-agent
📦 Auto-generated requirements: app/app_utils/.requirements.txt
╔═══════════════════════════════════════════════════════════╗
║ ║
║ 🤖 DEPLOYING AGENT TO VERTEX AI AGENT ENGINE 🤖 ║
║ ║
╚═══════════════════════════════════════════════════════════╝
📋 Deployment Parameters:
Project: YOUR_PROJECT_ID
Location: us-central1
Display Name: customer-support-agent
Min Instances: 1
Max Instances: 10
CPU: 4
Memory: 8Gi
Container Concurrency: 9
🌍 Environment Variables:
AGENT_VERSION: 0.1.0
GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY: true
GOOGLE_CLOUD_REGION: us-central1
NUM_WORKERS: 1
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT: true
INFO:root:Introspecting app.agent_runtime_app.agent_runtime via subprocess
🚀 Creating agent: customer-support-agent (this can take 5-10 minutes)...
INFO:vertexai_genai.agentengines:Using agent framework: google-adk
Operation: projects/.../locations/us-central1/reasoningEngines/.../operations/...
[... deployment in progress for ~5–10 minutes ...]
INFO:root:Agent Runtime ID written to deployment_metadata.json
✅ Deployment successful!
Agent Runtime ID: projects/.../locations/us-central1/reasoningEngines/XXXXXXXXXXXXXXXXXX
Service Account: service-XXXXXXXXX@gcp-sa-aiplatform-re.iam.gserviceaccount.com
📊 Open Console Playground: https://console.cloud.google.com/vertex-ai/agents/agent-engines/locations/us-central1/agent-engines/XXXXXXXXXXXXXXXXXX/playground?project=YOUR_PROJECT_ID
刚刚出现了什么情况?
代理运行时:
- 自动打包代码
- 已上传到 Google Cloud
- 预配的受管基础架构(4 个 CPU、8 Gi 内存)
- 配置了自动扩缩功能(1-10 个实例)
- 启用了遥测和可观测性
部署时间:约 5-10 分钟(一次性设置;后续重新部署速度更快)
11. 测试和监控已部署的智能体
您的代理现已在 Agent Runtime 上运行!我们来测试一下,并探索内置的监控功能。
测试智能体
方法 1:控制台 Playground(最简单)
agents-cli deploy 输出会显示一个控制台 Playground 链接,格式如下:
https://console.cloud.google.com/vertex-ai/agents/agent-engines/locations/<REGION>/agent-engines/<RUNTIME_ID>/playground?project=<PROJECT_ID>
(Agent Runtime 是产品化名称;底层 GCP 资源是 Vertex AI Agent Engine,因此网址路径中包含 vertex-ai/agents/agent-engines。)点击相应链接可执行以下操作:
- 登录 Google Cloud 控制台
- 查看已部署的智能体,并使用交互式聊天界面
- 测试查询,例如“旧金山的天气如何?”
- 实时查看工具调用和响应
控制台 Playground 提供了一种最简单的部署验证方法。
选项 2:agents-cli run –url
您在本地使用的同一 agents-cli run 命令也会查询已部署的代理:
RUNTIME_ID=$(jq -r .remote_agent_runtime_id deployment_metadata.json)
agents-cli run \
--url "https://us-central1-aiplatform.googleapis.com/v1/${RUNTIME_ID}" \
--mode adk \
"What's the weather in San Francisco?"
--mode adk 使用 ADK SSE 协议(部署的代理公开 :streamQuery)。agents-cli 自动附加来自有效 gcloud 凭据的 Google 访问令牌。
方法 3:Agent Engine SDK (Python)
如需通过 Python 以编程方式访问,请使用 Vertex AI SDK (vertexai.agent_engines) 的 Agent Engine 模块:
import vertexai
from vertexai import agent_engines
vertexai.init(project="YOUR_PROJECT_ID", location="us-central1")
# remote_agent_runtime_id from deployment_metadata.json (full resource name)
remote_agent = agent_engines.get(
"projects/.../locations/us-central1/reasoningEngines/..."
)
session = remote_agent.create_session(user_id="user-1")
for event in remote_agent.stream_query(
user_id="user-1",
session_id=session["id"],
message="What's the weather in San Francisco?",
):
print(event)
监控代理
代理运行时通过 Google Cloud 的监控工具提供内置的可观测性:
Cloud Trace - 请求跟踪
- 前往:Cloud 控制台 > Trace Explorer
- 选择您的项目
- 按属性
service.name = customer-support-agent过滤 span - 深入分析轨迹,查看模型推理、工具调用和端到端延迟时间
Cloud Logging - 应用日志
- 前往:Cloud 控制台 > 日志浏览器
- 使用查询:
resource.type="aiplatform.googleapis.com/ReasoningEngine" - 向此代理添加了
resource.labels.reasoning_engine_id="范围" - 查看智能体请求、响应、工具执行情况和错误
Cloud Monitoring - 指标和信息中心
- 前往:Cloud 控制台 > Metrics Explorer
- 按资源类型过滤
aiplatform.googleapis.com/ReasoningEngine - 实用指标:
request_count、request_latencies、instance_count
12. 可选:发布到 Gemini Enterprise
在 Gemini Enterprise 中为组织提供您的代理。
🤖 使用编码代理
向代理提出问题:
“将我的智能体发布到 Gemini Enterprise”
👤 手动模式
列出项目中的 Gemini Enterprise 应用,以便获取要定位的应用 ID:
agents-cli publish gemini-enterprise --list
然后注册已部署的代理。该命令会自动从 deployment_metadata.json 中读取代理运行时 ID:
agents-cli publish gemini-enterprise \
--gemini-enterprise-app-id "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/YOUR_APP_ID" \
--display-name "Customer Support Agent" \
--description "Answers weather and time questions" \
--tool-description "Use this tool to ask the customer support agent."
这会使您的智能体可供以下用户使用:
- 在 Gemini Enterprise 代理市场中
- 您组织中的用户
- 集中管理和治理
如需了解详情,请参阅发布文档。
13. 清理
为避免产生费用,请清理您创建的资源。
删除代理
从 deployment_metadata.json 获取 Agent Runtime 资源名称:
jq -r .remote_agent_runtime_id deployment_metadata.json
通过 Agent Engine SDK (Python) 删除
import vertexai
from vertexai import agent_engines
vertexai.init(project="YOUR_PROJECT_ID", location="us-central1")
# Full resource name from deployment_metadata.json
remote_agent = agent_engines.get(
"projects/.../locations/us-central1/reasoningEngines/..."
)
# force=True also deletes any child sessions
remote_agent.delete(force=True)
print("✅ Deleted successfully")
或者通过 REST API (curl):
RUNTIME_ID=$(jq -r .remote_agent_runtime_id deployment_metadata.json)
curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://us-central1-aiplatform.googleapis.com/v1beta1/${RUNTIME_ID}?force=true"
14. 恭喜!
🎉 您做到了!您已成功从头开始构建、测试和部署 AI 代理。
要点回顾
- 使用 Agents CLI 的两种方式(使用编码智能体或手动使用)
- 使用
agents-cli scaffold创建代理项目 - 构建带有自定义工具的智能体
- 使用 Playground 在本地进行测试
- 运行自动化评估
- 部署到 Agent Runtime(托管式基础架构)
- 使用 Cloud Trace 和 Cloud Logging 进行监控
- 生产最佳做法
您构建的内容
可用于生产用途的 AI 智能体,具备以下特点:
- 自然语言理解 (Gemini)
- 自定义工具集成
- 质量评估
- 自动扩缩部署
- 内置可观测性
后续步骤
扩展代理:
- 添加更多工具(数据库查询、API 调用)
- 使用向量搜索实现 RAG
- 添加多轮对话
- 启用 A2A(智能体间)通信
了解详情:
加入社区:
- GitHub 问题
- Stack Overflow
- 电子邮件:agents-cli@google.com
- 分享您的作品!