用 Google ADK 和 Llama 构建多 Agent 系统
展示如何用 Google Agent Development Kit 编排多个 agent 的协作。涵盖模型选型、编程模式和性能对比。
展示如何用 Google Agent Development Kit 编排多个 agent 的协作。涵盖模型选型、编程模式和性能对比。
Google 的 Agent Development Kit (ADK) 是最灵活、模块化的框架之一,用于构建真实场景中的 AI 智能体。虽然它针对 Gemini 和 Google 生态做了优化,但实际上它是模型无关、部署无关的,并且与第三方工具的兼容性惊人地好。
ADK 的设计目的是让 AI 智能体开发感觉更像软件开发,帮助你创建、部署和编排 AI 智能体工作流,无论是简单任务还是完整的生产级流水线。
如果你一直在探索如何将工具、模型和 API 组合成生产级 AI 智能体工作流,你一定会喜欢这套方案的轻量级特性(快速度更快)。
在本指南中,我将引导你使用 ADK 设置多智能体系统,集成 Tavily、Exa 和 Firecrawl 等工具。我们还将探索如何利用来自 Nebius AI Studio 的强大 LLM(如 Meta Llama 和 Nemotron-Ultra-253B-v1)来启动这个 AI 智能体流水线。
让我们深入了解 🚀
我还录制了一个完整的讲解视频和可用的 Colab 演示,你可以在按照指南学习的同时边看边学:
我们的多智能体系统利用了一套强大的工具、LLM 和平台:
Nebius AI Studio 是一个面向开发者和企业的强大推理即服务平台,旨在帮助他们高效地部署和扩展 AI 应用。它提供了全面的开源模型套件,包括 Llama 3.1 和 Nemotron Ultra 253B 等 LLM,以及 Flux Schnell 和 SDXL 等文生图模型。借助灵活的定价选项和可扩展的基础设施,Nebius AI Studio 使开发者能够高效地构建、调优和运行 AI 应用。
Meta 的 Llama 3.1 是一系列大型语言模型 (LLM),提供 8B、70B 和 405B 等多种参数规模。这些模型针对多语言对话做了优化,在行业基准测试中表现强劲。Llama 3.1 模型经过指令调优,适合用于文本生成、摘要生成和问题回答等任务。它还具有函数/工具调用能力,适合 AI 智能体应用场景。
你可以查看性能基准:
Nemotron Ultra 253B v1
Nemotron Ultra 253B v1 由 NVIDIA 开发,是一个大型语言模型,针对高级推理、人类聊天偏好以及 RAG 和工具调用等任务进行了微调。该模型基于 Meta 的 Llama 3.1 405B 衍生而来,支持长达 128K tokens 的上下文长度,针对高性能硬件部署做了优化。Nemotron Ultra 特别适合需要复杂推理、数学计算和工具集成的应用。
你可以查看评估分数和对比图:
Tavily 是一个针对大型语言模型 (LLM) 优化的搜索引擎,提供实时、准确和不偏不倚的信息。它通过在单个 API 调用中处理搜索、爬取、过滤和提取相关内容的复杂性,简化了将动态网络信息集成到 AI 驱动解决方案的过程。Tavily 支持检索增强生成 (RAG) 工作流,与 LangChain 和 LlamaIndex 等框架无缝集成。
Firecrawl 是一个工具,可将整个网站转换为 LLM 就绪的数据格式,如简洁的 markdown 或结构化的 JSON。它可以爬取无需站点地图的可访问子页面,并提供爬取、爬虫、映射和数据提取等功能。Firecrawl 与 Python、Node.js、LangChain 和 LlamaIndex 等多个 SDK 和框架集成,便于无缝集成到 AI 工作流。
Exa 是一个针对 AI 应用定制的神经搜索引擎,利用先进的 AI 语言处理技术返回最相关的网络内容。它结合了语义(基于嵌入)和关键词搜索功能,能进行精确的信息检索。Exa 的功能包括查找类似页面、提取简洁的 HTML 内容和直接回答查询,非常适合增强 AI 智能体的搜索能力。
Google 最近发布了 Agent-to-Agent (A2A) Protocol。这是一个开放标准,能够实现 AI 智能体之间的无缝通信和协作,无论它们的底层框架或供应商如何。通过使用标准化元数据(智能体卡片)和结构化消息,A2A 允许智能体发现彼此的能力、协调任务和安全地交换信息。该协议支持多种数据类型,包括文本、JSON 和文件,有助于跨多样化企业平台协调复杂工作流。
Agent Development Kit (ADK) 是一个开源框架,旨在简化 AI 智能体和多智能体系统的创建和部署。ADK 提供模块化架构,使开发者能够对智能体行为和编排进行细粒度控制。它支持与各种语言模型的集成,包括通过 Vertex AI 的 Google Gemini,并提供了丰富的工具和连接器集合,便于系统集成。
A2A 和 ADK 携手为开发者赋能,使其能够构建强大、互操作且可扩展的 AI 智能体生态系统,能够处理跨平台的复杂协作。
我们的应用拥有一个 SequentialAgent 工作流,由 Nebius 托管的 LLM(如 meta-llama/Meta-Llama-3.1-8B-Instruct 和 nvidia/Llama-3_1-Nemotron-Ultra-253B-v1)驱动,用于分析 AI 趋势,其中每个智能体按定义的顺序执行特定任务。
我们的 ADK Sequence 智能体应用将按如下顺序执行任务👇
ExaAgent:使用 Exa 从 Twitter/X 获取最新 AI 新闻和进展。
TavilyAgent:使用 Tavily 从 artificialanalysis.ai 检索 AI 基准、统计和分析。
SummaryAgent:合并并总结 ExaAgent 和 TavilyAgent 的发现。
FirecrawlAgent:使用 Firecrawl 从 Nebius AI Studio 主页爬取内容。
AnalysisAgent:分析所有收集的信息,包括 Nebius AI Studio 的产品,以识别趋势并推荐相关 AI 模型。
我们的 ADK Sequence 智能体应用(AI Trend Analyzer)工作流如下图所示👇
这种模块化方法确保了一个专注且可维护的系统,用于全面的 AI 趋势分析。
现在,让我们继续实现代码。 🔥
我用 Google Colab 和 VS Code 都实现了这个演示,但在本教程中,我将引导你通过 Colab 设置——这样更简单,上手也更快。
以下是如何安装所有必要的包和 SDK(包括 Google Agent Development Kit (ADK))以在 Google Colab 中顺利运行你的应用的步骤:
!pip install -q google-adk litellm python-dotenv exa-py tavily-python firecrawl-py
你可能想知道为什么我们需要安装 litellm 以及其他工具。这是因为,虽然 Google Agent Development Kit 严重依赖 Vertex AI、Gemini 和 Google 生态,但它也允许通过 LiteLLM 使用云、开源和专有 LLM。
LiteLLM 充当转译层,为来自 OpenAI、Anthropic、Nebius AI Studio 等多个提供商的超过 100 个 LLM 提供标准化的 OpenAI 兼容接口。这种集成使开发者能够访问多样化的模型集,而不受单个提供商的限制。
# 导入 Google ADK、LLM 和数据处理所需的库
from google.adk.models.lite_llm import LiteLlm
from google.adk.agents.llm_agent import LlmAgent
from google.adk.agents.sequential_agent import SequentialAgent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
# 导入用于数据检索和网络爬取的库
from exa_py import Exa
from tavily import TavilyClient
from firecrawl import FirecrawlApp
# 导入系统操作和时间处理的标准库
import os
from datetime import datetime, timedelta
from google.genai import types
os.environ["NEBIUS_API_BASE"] = "https://api.studio.nebius.ai/v1"
os.environ["NEBIUS_API_KEY"] = "your-api-key"
os.environ["EXA_API_KEY"] = "your-api-key"
os.environ["TAVILY_API_KEY"] = "your-api-key"
os.environ["FIRECRAWL_API_KEY"] = "your-api-key"
nebius_model = LiteLlm(
model="openai/meta-llama/Meta-Llama-3.1-8B-Instruct",
api_base=os.getenv("NEBIUS_API_BASE"),
api_key=os.getenv("NEBIUS_API_KEY")
)
现在初步设置已经完成,是时候定义我们的智能体将使用的工具了。我们将创建三个工具:
在 X(原 Twitter)上执行网络搜索的工具,
在 X(原 Twitter)上执行网络搜索的工具,
使用单个 URL 进行搜索的工具,
使用单个 URL 进行搜索的工具,
以及第三个工具来抓取 Nebius AI 网站的内容。
以及第三个工具来抓取 Nebius AI 网站的内容。
# 工具 1:定义一个函数,使用 Exa 在 X 上搜索 AI 相关新闻
def exa_search_ai(_: str) -> dict:
results = Exa(api_key=os.getenv("EXA_API_KEY")).search_and_contents(
query="Latest AI news OR new LLM models OR AI/Agents advancements",
include_domains=["twitter.com", "x.com"],
num_results=10,
text=True,
type="auto",
highlights={"highlights_per_url": 2, "num_sentences": 3},
start_published_date=(datetime.now() - timedelta(days=30)).isoformat()
)
return {"type": "exa", "results": [r.__dict__ for r in results.results]}
# 工具 2:定义一个函数,使用 Tavily 搜索 artificialanalysis.ai
def tavily_search_ai_analysis(_: str) -> dict:
client = TavilyClient(api_key=os.getenv("TAVILY_API_KEY"))
response = client.search(
query="AI benchmarks OR AI/LLM statistics OR AI providers analysis",
search_depth="advanced",
time_range="week",
include_domains=["artificialanalysis.ai"]
)
return {"type": "tavily", "results": response.get("results", [])}
# 工具 3:定义一个函数,使用 Firecrawl 抓取 Nebius AI 的内容
def firecrawl_scrape_nebius(_: str) -> dict:
firecrawl = FirecrawlApp(api_key=os.getenv("FIRECRAWL_API_KEY"))
try:
scrape_result = firecrawl.scrape_url(
url="https://studio.nebius.com/",
formats=["markdown"],
only_main_content=True
)
if scrape_result.success:
return {
"type": "firecrawl",
"markdown": scrape_result.markdown # ✅ 直接访问
}
else:
return {
"type": "firecrawl",
"error": "Scraping failed."
}
except Exception as e:
return {
"type": "firecrawl",
"error": str(e)
}
现在工具已经设置好,是时候定义我们的 AI 智能体了。我们将创建五个智能体,其中三个将使用特定工具来执行网络搜索和抓取任务,而两个智能体将处理结果的总结和深度分析。
该智能体使用 exa_search_ai 工具来收集关于 AI、LLM 进展和来自 X(原 Twitter)等平台的技术新闻的最新信息:
# 智能体 1:定义 Exa 智能体以从 X 获取最新 AI 更新
exa_agent = LlmAgent(
name="ExaAgent",
model=nebius_model,
description="Fetches latest AI news, LLMs, and advancements using Exa.",
instruction="""
Use the exa_search_ai tool to fetch the latest information about AI, new LLMs, and advancements in the field from Twitter and X.
Prefix your response with "**🔥ExaAgent:**"
""",
tools=[exa_search_ai],
output_key="exa_results"
)
该智能体使用 tavily_search_ai_analysis 工具来从 https://artificialanalysis.ai/ 获取 AI 相关的基准、性能统计数据和行业分析:
# 智能体 2:定义 Tavily 智能体以获取 AI 基准和相关信息
tavily_agent = LlmAgent(
name="TavilyAgent",
model=nebius_model,
description="Fetches AI benchmarks, statistics, and analysis using Tavily.",
instruction="""
Use the tavily_search_ai_analysis tool to retrieve benchmarks, statistics, llm providers and relevant analysis on AI.
Prefix your response with "**🐳TavilyAgent:**"
""",
tools=[tavily_search_ai_analysis],
output_key="tavily_results"
)
该智能体将 Exa 和 Tavily 智能体的输出总结并格式化为开发者友好的、富含 markdown 的总结:
# 智能体 3:定义总结智能体以合并和格式化来自 Exa 和 Tavily 智能体的结果
summary_agent = LlmAgent(
name="SummaryAgent",
model=nebius_model,
description="Summarizes and formats Exa and Tavily results.",
instruction="""
You are a summarizer and formatter.
- Combine the information from 'exa_results' and 'tavily_results'.
- Use markdown, bullet points, emojis (🚀, 📊, 📈).
- Prefix with "**🍥SummaryAgent:**"
""",
tools=[],
output_key="final_summary"
)
该智能体使用 firecrawl_scrape_nebius 工具从 Nebius AI Studio 首页抓取结构化内容,为分析做准备:
# 智能体 4:定义 Firecrawl 抓取智能体以抓取 Nebius AI Studio 的内容
firecrawl_agent = LlmAgent(
name="FirecrawlAgent",
model=nebius_model,
description="Scrapes Nebius Studio homepage using Firecrawl.",
instruction="""
Use the firecrawl_scrape_nebius tool to fetch markdown content from Nebius Studio website in proper format.
Prefix your response with "**🔥FirecrawlAgent:**"
""",
tools=[firecrawl_scrape_nebius],
output_key="firecrawl_content"
)
该智能体对总结的结果和抓取的 Nebius 内容进行深入分析。它识别关键 AI 趋势,将 LLM 功能与 Nebius 产品匹配,并使用 markdown 表格呈现见解。
在前面的步骤中,所有智能体都使用 meta-llama/Meta-Llama-3.1-8B-Instruct 模型来执行其分配的任务。然而,对于最终分析,我们需要一个更强大的 LLM 来处理更深入的见解和跨多个数据源的交叉引用。为此,我们切换到 nvidia/Llama-3_1-Nemotron-Ultra-253B-v1,这是目前最强大和最先进的模型之一,能够处理复杂的分析任务。
# 智能体 5:定义分析智能体以分析总结并提供见解,同时考虑 Nebius 抓取的数据
analysis_agent = LlmAgent(
name="AnalysisAgent",
model=LiteLlm(
model="openai/nvidia/Llama-3_1-Nemotron-Ultra-253B-v1",
api_base=os.getenv("NEBIUS_API_BASE"),
api_key=os.getenv("NEBIUS_API_KEY")
),
instruction="""
You are an AI analyst specializing in the latest AI trends and Large Language Models (LLMs).
- Analyze the 'final_summary', combining it with your knowledge of AI advancements and the information extracted from 'exa_results' and 'tavily_results'.
- Identify key trends, growth areas, and notable statistics related to AI and LLMs.
- Carefully examine the 'firecrawl_content', which contain data from Nebius AI Studio. This file provides details about available models on Nebius, including their names, pricing, token limits, and availability.
- Instead of focusing solely on model names, analyze the functional capabilities and intended use cases of LLMs mentioned in the 'final_summary'.
- Cross-reference the LLMs' functionalities with the Nebius AI Studio offerings in 'firecrawl_content', prioritizing models with similar features such as context window size, training data, or specialized capabilities.
- Utilize any available metadata in 'firecrawl_content', such as model descriptions, tags, or categories, for more accurate matching.
- If a relevant LLM is found on Nebius, provide a specific recommendation to the user, highlighting its features, pricing, token limits, and potential benefits based on the context from the 'final_summary'.
- If no exact match is found, suggest alternative Nebius models with the closest functional alignment to the desired capabilities.
- If a close match is found, suggest the possibility of fine-tuning the Nebius model to better align with the specific requirements.
- Present your analysis with clear and concise language, supported by quantifiable data and insights.
- Utilize markdown tables for statistics, as demonstrated below:
| Metric | Value |
|---|---|
| Growth Rate | 25% |
| Market Size | \$100 Billion |
- Always prefix your response with "**🔍AnalysisAgent:**" for clear identification.
""",
description="Analyzes the summary and presents insights and statistics.",
output_key="analysis_results"
)
在配置了所有单个智能体和工具后,下一阶段涉及将它们编排成一个有凝聚力的工作流。Google 的 Agent Development Kit (ADK) 通过 SequentialAgent 促进这一点,它确保每个智能体按预定义的顺序执行,并无缝地将输出传递给后续智能体。
SequentialAgent 充当编排器,以确定性序列管理子智能体的执行流。这种方法非常适合结构化 AI 工作流,其中一个智能体的输出为下一个智能体提供信息。在我们的设置中,管道包含五个智能体。
为了执行定义的管道,我们将 Runner 类与内存会话服务结合使用。此设置管理会话状态并促进智能体序列的执行。
以下是如何配置 SequentialAgent、会话和 Runner:
# This agent orchestrates the pipeline by running the sub_agents in order.
pipeline = SequentialAgent(
name="AIPipelineAgent",
sub_agents=[exa_agent, tavily_agent, summary_agent, firecrawl_agent, analysis_agent]
)
# Set up session and runner for the pipeline
APP_NAME = "ai_analysis_pipeline"
USER_ID = "colab_user"
SESSION_ID = "ai_analysis_session"
session_service = InMemorySessionService()
session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=pipeline, app_name=APP_NAME, session_service=session_service)
此配置为执行 AI 分析管道做好准备,确保每个智能体在定义的会话上下文中运行。
在使用 Google 的 Agent Development Kit (ADK) 配置和编排了所有智能体和工具后,现在是运行 AI 趋势分析管道的时候了。此步骤涉及启动智能体序列来执行获取 AI 新闻、分析基准、总结见解和抓取相关内容等任务。
我们首先定义一个函数,该函数向编排的智能体管道发送用户提示,并处理生成的事件:
# Define the main function to run the AI analysis
def run_ai_analysis():
content = types.Content(role="user", parts=[types.Part(text="Start the AI analysis")])
events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
for event in events:
if event.is_final_response():
print("📢 AI News Analysis and Insights:\n")
print(event.content.parts[0].text)
# Execute the AI analysis sequence
run_ai_analysis()
执行后,管道执行以下序列:
ExaAgent:从 X(原 Twitter)检索最新的 AI 新闻和更新。
ExaAgent:从 X(原 Twitter)检索最新的 AI 新闻和更新。
TavilyAgent:收集 AI 基准、统计数据和相关分析。
TavilyAgent:收集 AI 基准、统计数据和相关分析。
SummaryAgent:整合并格式化来自前面智能体的信息。
SummaryAgent:整合并格式化来自前面智能体的信息。
FirecrawlAgent:抓取 Nebius AI Studio 主页的内容。
FirecrawlAgent:抓取 Nebius AI Studio 主页的内容。
AnalysisAgent:分析汇总的数据和抓取的内容,以提供可行的见解。
AnalysisAgent:分析汇总的数据和抓取的内容,以提供可行的见解。
最终输出呈现了当前 AI 趋势、基准和模型分析的全面概览,帮助进行有根据的决策和战略开发,以下是响应的一部分:
哇🚀,现在你的 ADK 智能体应用已经准备好了。
在我们结束之前,值得强调的是 Google 的 Agent Development Kit (ADK) 提供的不仅仅是命令行工具。通过运行 adk web,你可以访问一个全面的 Web UI,这会增强开发体验:
可视化流程图:通过直观的图表了解智能体工作流。
可视化流程图:通过直观的图表了解智能体工作流。
交互式调试:实时检查智能体状态、输入和输出。
交互式调试:实时检查智能体状态、输入和输出。
评估工具:创建和管理评估集来测试智能体性能。
评估工具:创建和管理评估集来测试智能体性能。
部署选项:轻松将智能体部署到 Google Cloud Run 或 Vertex AI Agent Engine 等平台。
部署选项:轻松将智能体部署到 Google Cloud Run 或 Vertex AI Agent Engine 等平台。
这个集成界面简化了构建、测试和部署 AI 智能体的过程,使 ADK 成为开发者的强大工具。
以下是我之前构建的简单 ADK 智能体应用执行时 Web UI 的演示:
在本教程中,我们探讨了如何使用 Google 的 Agent Development Kit (ADK) 构建多智能体 AI 分析管道。通过整合 Exa、Tavily、Firecrawl 和 Nebius AI Studio 等工具,我们展示了如何编排智能体以执行实时网页搜索、内容抓取、总结和深度分析等任务。
利用 ADK 的功能,包括用于可视化和评估的 Web UI,开发者可以针对各种用例精心打造可扩展、模块化和交互式的 AI 智能体。此框架不仅简化了收集和分析 AI 相关信息的过程,还展示了编排智能体在现实世界中的实际应用。
无论你是在探索 AI 趋势、自动化研究工作流还是开发智能应用,此设置都提供了一个坚实的基础来进一步构建。
准备好提升你的 AI 智能体水平吗?深入了解 ADK 并立即开始构建。
Astrodevil / ADK-Agent-Examples
使用不同工具构建的智能体应用示例——由 Google 的 Agent Development Kit (ADK) 和 Nebius Token Factory 提供支持。
完整讲解视频可在 YouTube 上获得 - Analyzer Agent + ADK Intro、Job Finder Agent (MistralOCR + Qwen3)。阅读详细博客 1 和博客 2
此存储库包含使用 Google 的 ADK (Agent Development Kit) 构建的各种智能体演示...