1. 本实验的目标
在本实操实验中,您将构建一个多代理应用,该应用会根据您的提示生成图片,并根据您的提示评估该图片。如果生成的图片未能令人满意地满足提示中所述的要求,代理会持续生成图片,直到生成符合您要求的图片为止。在此实践中,每个代理都有一个单一用途,这些代理相互协作以实现总体目标。
学习内容
- 了解 ADK 的基础知识,并学习如何创建多智能体系统。
- 了解如何在 GCP 中轻松部署和使用代理。
- 了解 A2A 协议的基础知识
- 了解如何将 A2A 协议和 ADK 结合使用来创建开放式智能体。
2. 准备工作
- 如果您还没有可用的项目,则需要在 GCP 控制台中创建一个新项目。
- 在本实验中,我们将使用 GCP Cloud Shell 来执行任务。打开 Cloud Shell 并使用 Cloud Shell 设置项目。
- 按 Cloud Shell 编辑器按钮,打开 GCP Cloud Shell 编辑器。如果您看到“授权 Shell”弹出式窗口,请点击以授权 Cloud Shell 编辑器。
- 您可以使用以下命令检查项目是否已通过身份验证。
gcloud auth list
- 在 Cloud Shell 中运行以下命令,以确认您的项目
gcloud config list project
- 如果项目未设置,请使用以下命令进行设置
gcloud config set project <YOUR_PROJECT_ID>
- 我们需要启用一些服务才能运行本实验。在 Cloud Shell 中运行以下命令。
gcloud services enable aiplatform.googleapis.com
3. 概览:智能体开发套件的优势
智能体开发套件为构建智能体应用的开发者提供了多项关键优势:
- 多智能体系统:通过以分层方式组合多个专用智能体来构建模块化且可扩缩的应用。实现复杂的协调和委托。
- 丰富的工具生态系统:为代理配备各种功能:使用预构建的工具(搜索、代码执行等)、创建自定义函数、集成第三方代理框架(LangChain、CrewAI)中的工具,甚至将其他代理用作工具。
- 灵活的编排:使用工作流代理(
SequentialAgent
、ParallelAgent
和LoopAgent
)定义工作流,以实现可预测的流水线;或者利用 LLM 驱动的动态路由(LlmAgent
转移)来实现自适应行为。 - 集成式开发者体验:使用强大的 CLI 和交互式开发界面在本地进行开发、测试和调试。逐步检查事件、状态和代理执行情况。
- 内置评估:通过针对预定义的测试用例评估最终回答质量和逐步执行轨迹,系统地评估智能体性能。
- 可随时部署:将智能体容器化并部署到任何位置 - 在本地运行、使用 Vertex AI Agent Engine 进行扩缩,或使用 Cloud Run 或 Docker 集成到自定义基础架构中。
虽然其他生成式 AI SDK 或代理框架也允许您查询模型,甚至为模型提供工具,但要在多个模型之间实现动态协调,您需要完成大量工作。
智能体开发套件提供的框架比这些工具更高级别,可让您轻松地将多个智能体相互连接,以实现复杂但易于维护的工作流程。
4. A2A 简介
Agent2Agent (A2A) 协议是一种开放标准,旨在实现不同框架、供应商和网域的自主 AI 代理之间的无缝安全通信和协作。
- 通用互操作性:A2A 使智能体能够协同工作,无论其底层技术如何,从而打造真正的多智能体生态系统。这意味着,不同公司在不同平台上构建的代理可以进行通信和协调。
- 功能发现:代理可以使用“代理卡片”(JSON 文档) 宣传其功能,其中包含代理的身份、支持的 A2A 功能、技能和身份验证要求。这样,其他代理就可以发现并选择最适合给定任务的代理。
- 默认安全:安全是一项核心原则。A2A 采用企业级身份验证和授权机制,利用 HTTPS/TLS、JWT、OIDC 和 API 密钥等标准来确保安全互动并保护敏感数据。
- 模态无关:该协议支持各种通信模态,包括文本、音频和视频流,以及互动表单和嵌入式 iframe。这种灵活性使代理能够以最适合任务和用户的格式交换信息。
- 结构化任务管理:A2A 为任务委派、监控和完成定义了清晰的协议。它支持对相关任务进行分组,并使用唯一的任务 ID 在不同代理之间管理这些任务。任务可以经历已定义的生命周期(例如,已提交、正在处理、已完成)。
- 不透明执行:一个重要特征是,代理无需向其他代理透露其内部推理过程、内存或特定工具。它们仅公开可调用的服务,从而提高模块化程度和隐私保护能力。
- 基于现有标准:A2A 利用了成熟的网络技术,例如 HTTP、用于实时流式传输的服务器发送事件 (SSE) 和用于结构化数据交换的 JSON-RPC,从而更易于与现有 IT 基础架构集成。
- 异步通信:该协议在设计时主要考虑了异步通信,可实现灵活的任务进度,即使未持续保持连接,也能推送更新通知。
5. 代理架构
在本实验中,您将创建一个多代理应用,该应用会根据您的要求生成图片,并在向您展示图片之前对其进行评估。
该系统采用结构化设计,包含一个名为 image_scoring 的主代理,用于协调整个流程。此主代理有一个名为 image_generation_scoring_agent 的子代理,而该子代理本身也有自己的子代理,用于执行更具体的任务。这样一来,主代理会将任务委托给其子代理,从而形成分层关系。 图 2:代理的总体流程。
所有代理的列表
- image_scoring(主要代理):
- 用途:这是管理整个工作流的根代理。它会以循环方式反复运行 image_generation_scoring_agent 和 checker_agent,直到满足终止条件。
- 分代理:
- image_generation_scoring_agent
- checker_agent_instance
- image_generation_scoring_agent(image_scoring 的子代理):
- 用途:此代理负责生成图片和为图片评分的核心逻辑。它会执行一系列三个子代理来实现此目的。
- 分代理:
- image_generation_prompt_agent
- image_generation_agent
- scoring_images_prompt
- checker_agent_instance(image_scoring 的子代理):
- 用途:此代理会检查图片评分流程是否应继续或终止。它使用 check_tool_condition 工具来评估终止条件。
- image_generation_prompt_agent(image_generation_scoring_agent 的子代理):
- 用途:此代理擅长创建图片生成提示。它接受输入文本,并生成适合图片生成模型的详细提示。
- image_generation_agent(image_generation_scoring_agent 的子代理):
- 用途:此代理擅长使用 Imagen 3 创建图片。它从 image_generation_prompt_agent 获取提示,然后生成图片。
- scoring_images_prompt(image_generation_scoring_agent 的子代理):
- 用途:此代理擅长根据各种标准评估图片并为其评分。它会获取生成的图片并为其分配得分。
代理使用的工具
- check_tool_condition:
- 说明:此工具用于检查是否满足循环终止条件,或者是否已达到最大迭代次数。如果满足上述任一条件,则停止循环。
- 由 checker_agent_instance 使用
- generate_images:
- 说明:此工具使用 Imagen 3 模型生成图片。它还可以将生成的图片保存到 Google Cloud Storage 存储分区。
- 使用者:image_generation_agent
- get_policy:
- 说明:此工具可从 JSON 文件中提取政策。image_generation_prompt_agent 使用该政策来创建图片生成提示,scoring_images_prompt 使用该政策来对图片进行评分。
- 由以下内容使用:image_generation_prompt_agent、scoring_images_prompt
- get_image:
- 说明:此工具用于加载生成的图片制品,以便对其进行评分。
- 使用者:scoring_images_prompt
- set_score:
- 说明:此工具用于在会话状态中设置所生成图片的总得分。
- 使用者:scoring_images_prompt
6. 任务 1. 安装 ADK 并设置环境
在此实践中,我们将使用 Cloud Shell 来执行任务。
启用 Vertex AI 推荐的 API
- 在 Google Cloud 控制台顶部搜索并前往 Vertex AI。
- 点击启用所有推荐的 API。
准备 Cloud Shell 编辑器标签页
- 选择 Google Cloud 控制台窗口后,按下键盘上的 G 键,然后按下 S 键,打开 Cloud Shell。或者,您也可以点击 Google Cloud 控制台右上角的 Cloud Shell 按钮
。
- 点击继续。
- 当系统提示您授权 Cloud Shell 时,请点击授权。
- 在 Cloud Shell 窗格的右上角,点击在新窗口中打开按钮
。
- 点击窗格顶部的打开编辑器铅笔图标 (
) 以查看文件。
- 在左侧导航菜单顶部,点击“资源管理器”图标
以打开文件资源管理器。
- 点击打开文件夹按钮。
- 在本实验的其余部分,您可以在此窗口中将 Cloud Shell 编辑器和 Cloud Shell 终端用作 IDE。
下载并安装本实验的 ADK 和代码示例
- 执行以下命令,从 GitHub 克隆所需的源代码并安装必要的库。
#create the project directory mkdir imagescoring cd imagescoring #clone the code in the local directory git clone https://github.com/haren-bh/multiagenthandson.git #Create the virtual environment python3 -m venv pythonenv source pythonenv/bin/activate #install google-adk and a2a sdk python3 -m pip install google-adk==1.8.0 python3 -m pip install a2a-sdk==0.2.16
- 我们将使用 Poetry 安装其他要求:
cd multiagenthandson #go to the application directory pip install poetry poetry-plugin-export poetry install --with deployment
- 如果您没有 Cloud Storage 存储分区,请在 Google Cloud Storage 中创建一个新存储分区。您还可以使用 gsutil 命令创建存储分区。
gsutil mb gs://YOUR-UNIQUE-BUCKETNAME
- 在编辑器中,依次前往“View”->“Toggle hidden files”。在 image_scoring 文件夹中创建一个包含以下内容的 .env 文件。添加必需的详细信息,例如项目名称和 Cloud Storage 存储分区。
GOOGLE_GENAI_USE_VERTEXAI=1 #1 if VERTEXAI has to be used. Can be 0 if API_KEY is specified
GOOGLE_CLOUD_PROJECT=YOUR CLOUD PROJECT NAME
GOOGLE_CLOUD_LOCATION=us-central1
GOOGLE_CLOUD_STORAGE_BUCKET=YOUR BUCKET NAME # Only required for deployment on Agent Engine
GCS_BUCKET_NAME=YOUR BUCKET NAME #Bucket for storing generated images.
SCORE_THRESHOLD=40 # Min threshold for image_score. Max Score is 50 , hence should be less than 50.
#If the computed score is higher then loop will terminate
#MAX_ITERATIONS=5 #Max iterations for evaluating the image_score before terminating the loop.
IMAGEN_MODEL="imagen-3.0-generate-002"
GENAI_MODEL="gemini-2.5-flash"
#AGENT_ENGINE_ID=<AGENT_ENGINE_ID> #The Agent Engine ID obtained after deploying to the agent engine.
- 查看源代码中的代理结构,从 agent.py 开始。此代理包含将连接到其他代理的根代理。
- 在终端中返回到顶级目录 multiagenthandson,然后执行以下命令以在本地运行代理
# Run the following command to run agents locally export GCS_BUCKET_NAME=your gcs bucket name adk web
图 1
在终端上按住 Ctrl 键并点击 (CMD+Click for MacOS) 显示的 http:// 网址,以打开基于浏览器的 ADK GUI 客户端。它应如图 2 所示
- 让我们生成一些图片。您可以尝试使用以下提示,也可以使用自己的提示。
- 日落时宁静的山景
- 一只骑自行车的猫
图 2
7. 任务 2. 部署到 Agent Engine
现在,我们将代理部署到 Agent Engine。Agent Engine 是一项全托管式服务,用于在 GCP 中部署代理。Agent Engine 与 ADK 兼容,因此使用 ADK 构建的代理可以部署在 Agent Engine 中。
- 定义一些环境变量
export GOOGLE_CLOUD_LOCATION='us-central1' export GOOGLE_CLOUD_PROJECT='your project id'
- 使用 Poetry 创建 requirements.txt 文件。Poetry 将使用 pyproject.toml 创建 requirements.txt 文件。运行命令后,检查是否已创建 requirements.txt 文件。
# Go to the parent folder containing pyproject.toml file # install poetry-plugin-export pip install poetry-plugin-export #Create requirements.txt file poetry export -f requirements.txt --output requirements.txt --without-hashes
- 创建软件包。我们需要将应用打包到 .whl Python 软件包中。我们将使用诗歌来做到这一点。执行命令后,请确保创建了 dist 文件夹,并且其中包含 .whl 文件。
# Go to the parent folder containing pyproject.toml file #Create python package, to create whl file poetry build
- 现在,我们将准备部署脚本。部署脚本将部署我们的图片评分代理或代理引擎服务。请将 image_scoring 文件夹中 deploy.py 的内容更改为如下所示。
# Change the content of the following. Look for #change this comment
import vertexai
from .agent import root_agent
import os
import glob # To easily find the wheel file
PROJECT_ID = "YOUR PROJECT ID" #change this your project
LOCATION = "us-central1" #change this
STAGING_BUCKET = "gs://YOUR BUCKET " #change this to your bucket
from vertexai import agent_engines
vertexai.init(
project=PROJECT_ID,
location=LOCATION,
staging_bucket=STAGING_BUCKET,
)
remote_app = agent_engines.create(
agent_engine=root_agent,
requirements=open(os.path.join(os.getcwd(), "requirements.txt")).readlines()+["./dist/image_scoring-0.1.0-py3-none-any.whl"],#change this to your local location
extra_packages=[
"./dist/image_scoring-0.1.0-py3-none-any.whl", # change this to your location
]
)
print(remote_app.resource_name)
- 我们现在可以运行部署脚本了。
#run deploy script from the parent folder containing deploy.py python3 -m image_scoring.deploy
部署后,您应该会看到类似以下内容,
图 3
- 现在,我们来测试已部署的代理。为了测试远程部署的代理引擎,请先从终端的部署输出中复制代理位置。它应如下所示:projects/85469421903/locations/us-central1/reasoningEngines/7369674597261639680。
前往 testclient 文件夹,打开 remote_test.py 文件并修改以下行。
PROJECT_ID = "" #change this LOCATION = "" #change this STAGING_BUCKET = "" #change this #replace the id with your own. reasoning_engine_id="your agent engine id" #You can replace this with your own prompt image_prompt="A cat riding a bicycle" #execute remote_test.py python3 remote_test.py
8. 任务 3. 创建 A2A 智能体
在此步骤中,我们将基于之前步骤中创建的代理创建一个简单的 A2A 代理。现有 ADK agent 可以根据 A2A 协议发布。以下是您将在本步骤中学习的关键内容。
- 了解 A2A 协议的基础知识。
- 了解 ADK 和 A2A 协议如何协同工作。
- 了解如何与 A2A 协议互动。
在此实践中,我们将使用 image_scoring_adk_a2a_server 文件夹中的代码。在开始任务之前,请将目录更改为此文件夹。
创建 A2A 智能体卡片
A2A 协议需要一个代理卡,其中包含有关代理的所有信息,例如代理功能、代理使用指南等。部署 A2A 代理后,可以使用“.well-known/agent-card.json”链接查看代理卡。客户端可以参考此信息向代理发送请求。
在 remote_a2a/image_scoring 文件夹中,确认是否存在包含以下内容的 agents.json。
{
"name": "image_scoring",
"description": "Agent that generates images based on user prompts and scores their adherence to the prompt.",
"url": "http://localhost:8001/a2a/image_scoring",
"version": "1.0.0",
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["image/png", "text/plain"],
"capabilities": {
"streaming": true,
"functions": true
},
"skills": [
{
"id": "generate_and_score_image",
"name": "Generate and Score Image",
"description": "Generates an image from a given text prompt and then evaluates how well the generated image adheres to the original prompt, providing a score.",
"tags": ["image generation", "image scoring", "evaluation", "AI art"],
"examples": [
"Generate an image of a futuristic city at sunset",
"Create an image of a cat playing a piano",
"Show me an image of a serene forest with a hidden waterfall"
]
}
]
}
创建 A2A 代理
在根文件夹 image_scoring_adk_a2a_server 中,确认是否存在 a2a_agent.py 文件,该文件是 a2a 代理的入口点。它应包含以下内容:
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
root_agent = RemoteA2aAgent(
name="image_scoring",
description="Agent to give interesting facts.",
agent_card="http://localhost:8001/a2a/image_scoring/.well-known/agent.json",
# Optional configurations
timeout=300.0, # HTTP timeout (seconds)
httpx_client=None, # Custom HTTP client
)
运行 A2A 智能体
现在,我们准备好运行代理了!如需运行代理,请从顶级文件夹 image_scoring_adk_a2a_server 内执行以下命令
#set some environmental variables export GOOGLE_CLOUD_PROJECT=datapipeline-372305 export GOOGLE_CLOUD_LOCATION=us-central1 export GCS_BUCKET_NAME=haren-genai-bucket #following command runs the ADK agent as a2a agent adk api_server --a2a --port 8001 remote_a2a
测试 A2A 代理
代理运行后,我们现在可以去测试代理了。首先,我们先来查看代理卡片。
#Execute the following curl http://localhost:8001/a2a/image_scoring/.well-known/agent.json
执行上述操作后,应该会显示我们 A2A 代理的代理卡片,该卡片主要是我们在上一步中创建的 agent.json 的内容。
现在,我们向代理发送请求。我们可以使用 curl 向代理发送请求,
curl -X POST http://localhost:8001/a2a/image_scoring -H 'Content-Type: application/json' -d '{ "id": "uuid-123", "params": { "message": { "messageId": "msg-456", "parts": [{"text": "Create an image of a cat"}], "role": "user" } } }'
在上述请求中,您可以更改“Create an image of a cat”(创作一张猫的图片)这一行来更改提示。运行该命令后,您可以在指定的 Google Cloud Storage 中查看输出映像。
9. 清理
现在,我们来清理刚刚创建的内容。
- 删除我们刚刚创建的 Agent Engine 服务器。在 Google Cloud 控制台的搜索栏中输入“Vertex AI”,前往 Vertex AI。点击左侧的“代理引擎”。您可以点击“删除”来删除代理。
图 4
- 删除 Cloud Shell 中的文件
#Execute the following to delete the files rm -R imagescoring
- 删除存储分区。您可以前往 GCP 控制台->Cloud Storage,选择并删除您的存储分区。