AI智能体(八):构建多智能体系统
神译局是36氪旗下编译团队,关注科技、商业、职场、生活等领域,重点介绍国外的新技术、新观点、新风向。
编者按:2025年是AI智能体元年。本系列文章旨在介绍AI智能体的概念、类型、原理、架构、开发等,为进一步了解AI智能体提供入门知识。本文为系列文章的第八篇,文章来自编译。
1. 引言
在评估智能体能在什么地方创造价值时,可优先考虑那些传统方法难以实现自动化、特别是会遇到瓶颈的工作流:
复杂决策: 涉及微妙判断、例外情况或依赖上下文决策的工作流,比方说客户服务流程中的退款审批。
难以维护的规则: 因规则集庞大且复杂而导致更新成本高或易出错、变得难以管理的系统,比方说执行供应商安全审查。
严重依赖非结构化数据: 涉及解释自然语言、从文档中提取含义或与用户进行对话式交互的场景,比方说处理家庭保险理赔。 在决定构建智能体之前,务必明确确认你的用例能满足上述条件。否则,一个确定性的解决方案可能就足够了。
2. 智能体设计组件
就最基本形式而言,智能体包含了三个核心组件:
模型 (Model): 为智能体的推理和决策提供动力的 LLM。
工具 (Tools): 智能体可用于执行操作的外部函数或 API。
指令 (Instructions): 定义智能体行为方式的明确指导方针和防护措施。
2.1 选择模型
不同的模型在任务复杂性、延迟和成本方面有不同的优势和权衡。并非每个任务都需要最智能的模型——一个简单的检索或意图分类任务可能由更小、更快的模型处理,而像决定是否批准退款这样的困难任务则可能受益于能力更强的模型。 一个行之有效的方法是:在构建智能体原型时,为每个任务使用能力最强的模型,以建立性能基准。然后,尝试用小一点的模型替换,看看是否仍能达到可接受的结果。这样,你就不会过早限制智能体的能力,并且可以诊断出小一点的模型什么时候能行什么时候行不通。 总之,选择模型的原则很简单:
建立评估机制,设定性能基准。
专注于用当前可用的最佳模型达到准确度目标。
在可能的情况下,用更小的模型替换更大的模型,以优化成本和延迟。
什么是函数调用最好的小模型?
选项通常可以从任何开源模型开始,如 Llama、Mistral、Qwen、Claude Opus 等。
2.2 定义工具
函数调用 (Function calling) 是让大模型 (LLMs) 与工具交互的主要方式。你经常会看到“函数 (Function)”和“工具 (Tool)”可以互换使用,因为“函数”(可重用的代码块)就是智能体用来执行任务的“工具”。
工具通过利用底层应用或系统的 API 来扩展智能体的能力。对于没有 API 的遗留系统,智能体可以依靠计算机使用模型 (computer-use models),像人类一样通过网页和应用 UI 直接与这些应用和系统交互。每个工具都应有一个标准化的定义,从而实现工具与智能体之间灵活的多对多关系。文档完善、经过充分测试且可重用的工具可以提高可发现性、简化版本管理并防止重复定义。
广义上而言,智能体需要三种类型的工具:
比方说,在使用 Agents SDK 时,你可以这样为上面定义的智能体配备一系列工具:
Python
from agents import Agent, WebSearchTool, function_tool
@function_tool
def save_results(output):
db.insert({"output": output, "timestamp": datetime.time()})
return "文件已保存"
search_agent = Agent(
name="搜索智能体",
instructions="帮助用户搜索互联网,并在要求时保存结果。",
tools=[WebSearchTool(), save_results],
)
随着所需工具数量的增加,可以考虑将任务拆分给多个智能体。
2.3 配置指令
高质量的指令对于任何基于 LLM 的应用都至关重要,对于智能体尤其如此。清晰的指令可以减少歧义,改进智能体的决策,从而实现更流畅的工作流执行和更少的错误。
你可以使用高级模型,如 o1 或 o3-mini,根据现有文档自动生成指令。以下是一个说明这种方法的示例提示:
3. 编排
在具备了基础组件之后,你就可以考虑编排模式,好让智能体能够有效地执行工作流。
多智能体系统可以建模成图(graph),智能体表示为节点(node)。在管理者和监督者模式中,边(edge)代表工具调用(tool calls);而在去中心化和军团模式中,边代表交接(handoffs),即在智能体之间转移执行权。
不管采用哪种编排模式,AI智能体工作过程通常遵循以下4个步骤:
1. 接收输入:智能体获取用户或环境的指令。
2. 推理: 智能体处理输入、评估当前状态,并决定后续动作。
3. 执行动作: 智能体执行决策,如调用工具、生成响应或与其他智能体互动。
4. 输出结果: 智能体将执行结果反馈给用户或系统。
无论采用何种编排模式,核心原则都是一样的:保持组件灵活可变、可组合,并由清晰、结构良好的提示驱动。
在去中心化模式中,智能体可以彼此“交接”(handoff)工作流的执行权。交接是一种单向转移,允许一个智能体将任务委托给另一个智能体。
4. 实现:监督者模式
创建一个监督者智能体(supervisor agent)来编排多个专业化的智能体。
```python
pip install langgraph-supervisor langchain-openai
export OPENAI_API_KEY=<你的API密钥>
from langchain_openai import ChatOpenAI
from langgraph.graph import START, END
from langchain_community.tools.tavily_search import TavilySearchResults
from langgraph.prebuilt import create_react_agent
from langgraph_supervisor import create_supervisor
from IPython.display import Image, display
import os
# 选择语言模型
model = ChatOpenAI(model="gpt-4o", api_key=os.getenv("OPENAI_API_KEY"))
# 定义工具
def add(a: float, b: float) -> float:
"""将两个数字相加。"""
return a + b
def multiply(a: float, b: float):
"""将两个数字相乘。"""
return a * b
def divide(a: float, b: float):
"""将两个数字相除。"""
return a / b
tavily_api_key = os.getenv("TAVILY_API_KEY", "你的Tavily API密钥")
web_search = TavilySearchResults(max_results=3, tavily_api_key=tavily_api_key)
# 创建工作智能体 (Worker Agents)
research_agent = create_react_agent(
model=model,
tools=[web_search],
name="research_agent",
prompt=(
"你是一个研究型智能体。\n\n"
"指令:\n"
"- 只协助完成与研究相关的任务,切勿执行任何数学计算\n"
"- 完成任务后,直接回复监督者\n"
"- 回复内容仅包含你的工作结果,不要包含任何其他文本。"
)
)
math_agent = create_react_agent(
model=model,
tools=[add, multiply, divide],
name="math_agent",
prompt=(
"你是一个数学智能体。\n\n"
"指令:\n"
"- 只协助完成与数学相关的任务\n"
"- 完成任务后,直接回复监督者\n"
"- 回复内容仅包含你的工作结果,不要包含任何其他文本。"
)
)
# 创建监督者智能体 (Supervisor Agent)
supervisor_agent = create_supervisor(
model=model,
agents=[research_agent, math_agent],
prompt=(
"你是一个监督者,管理着两个智能体:\n"
"- 一个研究智能体。将研究相关任务分配给这个智能体\n"
"- 一个数学智能体。将数学相关任务分配给这个智能体\n"
"一次只分配给一个智能体工作,不要并行调用智能体。\n"
"你自己不要执行任何工作。"
),
add_handoff_back_messages=True,
output_mode = "full_history",
).compile() # 编译图
# 显示图结构 (可选)
display(Image(supervisor_agent.get_graph().draw_mermaid_png()))
```
我们用 `pretty_print_messages` 辅助函数来美化渲染智能体流式输出:
```python
from langchain_core.messages import convert_to_messages
def pretty_print_message(message, indent=False):
"""美化打印消息内容"""
pretty_message = message.pretty_repr(html=True)
if not indent:
print(pretty_message)
return
indented = "\n".join("\t" + c for c in pretty_message.split("\n"))
print(indented)
def pretty_print_messages(update, last_message=False):
"""批量美化打印消息更新"""
is_subgraph = False
if isinstance(update, tuple):
ns, update = update
# 跳过父图的更新打印
if len(ns) == 0:
return
graph_id = ns[-1].split(":")[0]
print(f"来自子图 {graph_id} 的更新:")
print("\n")
is_subgraph = True
for node_name, node_update in update.items():
update_label = f"来自节点 {node_name} 的更新:"
if is_subgraph:
update_label = "\t" + update_label
print(update_label)
print("\n")
messages = convert_to_messages(node_update["messages"])
if last_message:
messages = messages[-1:]
for m in messages:
pretty_print_message(m, indent=is_subgraph)
print("\n")
```
测试该工作流:
```python
def test_supervisor_functionality():
"""测试监督者模式功能,使用特定GDP查询验证交接过程。"""
query = "查询:查找美国和纽约州2024年的GDP。纽约州GDP占美国GDP的百分比是多少?"
print(query)
print("-" * 80)
try:
# 模拟用户输入进行流式处理
for chunk in supervisor_agent.stream(
{
"messages": [
{
"role": "user",
"content": "查找美国和纽约州2024年的GDP。纽约州GDP占美国GDP的百分比是多少?",
}
]
},
subgraphs=False # 不显示子图内部细节
):
pretty_print_messages(chunk, last_message=True) # 只打印最后一个有意义的消息
print(f"测试成功完成")
except Exception as e:
print(f"测试失败,错误信息: {str(e)}")
print("=" * 80)
# 运行测试
if __name__ == "__main__" or True: # 允许在笔记本中直接运行
test_supervisor_functionality()
```
输出示例:
```
查询:查找美国和纽约州2024年的GDP。纽约州GDP占美国GDP的百分比是多少?
--------------------------------------------------------------------------------
来自节点 supervisor 的更新:
================================= 工具消息 =================================
名称: transfer_to_research_agent
成功交接给 research_agent
来自节点 research_agent 的更新:
================================= 工具消息 =================================
名称: transfer_back_to_supervisor
成功交回给 supervisor
来自节点 supervisor 的更新:
================================= 工具消息 =================================
名称: transfer_to_math_agent
成功交接给 math_agent
来自节点 math_agent 的更新:
================================= 工具消息 =================================
名称: transfer_back_to_supervisor
成功交回给 supervisor
来自节点 supervisor 的更新:
================================== AI 消息 ==================================
名称: supervisor
2024年,纽约州GDP约占美国GDP的8.15%。
测试成功完成
================================================================================
```
4.1 消息历史管理
智能体的消息如何添加到多智能体系统的整体对话历史当中是可以控制的:
* 包含智能体的完整消息历史:
```python
supervisor = create_supervisor(
agents=[agent1, agent2],
output_mode="full_history" # 输出模式:完整历史
)
```
* 仅包含智能体的最终响应:
```python
supervisor = create_supervisor(
agents=[agent1, agent2],
output_mode="last_message" # 输出模式:仅最后一条消息
)
```
4.2 多层结构
你可以通过创建一个管理多个监督者的监督者,来构建多层系统:
research_team = create_supervisor(
[research_agent, math_agent],
model=model,
supervisor_name="research_supervisor"
).compile(name="research_team")
writing_team = create_supervisor(
[writing_agent, publishing_agent],
model=model,
supervisor_name="writing_supervisor"
).compile(name="writing_team")
top_level_supervisor = create_supervisor(
[research_team, writing_team],
model=model,
supervisor_name="top_level_supervisor"
).compile(name="top_level_supervisor")
4.3 自定义交接工具
默认情况下,监督者使用预建的 `create_handoff_tool` 函数创建的交接工具(handoff tools)。你也可以创建自己的自定义交接工具。以下是一些修改默认实现的想法:
更改工具名称和/或描述: 让工具名和描述更符合你的业务场景。
添加工具调用参数: 让 LLM 填写参数,比方说为下一个智能体添加任务描述。
更改交接时传递给子智能体的数据: 默认情况下,`create_handoff_tool` 会传递完整的消息历史(监督者到此时生成的所有消息)以及一个指示交接成功的工具消息。你可以修改这个行为。
以下是如何将自定义的交接工具传递给 `create_supervisor` 的示例:
from langgraph_supervisor import create_handoff_tool
workflow = create_supervisor(
[research_agent, math_agent],
tools=[
create_handoff_tool(agent_name="math_expert", name="assign_to_math_expert", description="Assign task to math expert"),
create_handoff_tool(agent_name="research_expert", name="assign_to_research_expert", description="Assign task to research expert")
],
model=model,
)
还可以控制交接工具消息是否添加到状态,默认情况下,交接工具调用的消息会被添加到状态历史中 (`add_handoff_messages=True`)。你可以禁用此功能,让历史记录变得更简洁::
workflow = create_supervisor(
[research_agent, math_agent],
model=model,
add_handoff_messages=False
)
还可以自定义自动生成的交接工具的前缀:
workflow = create_supervisor(
[research_agent, math_agent],
model=model,
handoff_tool_prefix="delegate_to"
)
# This will create tools named: delegate_to_research_expert, delegate_to_math_expert
自定义交接工具的实现示例:
```python
from typing import Annotated
from langchain_core.tools import tool, InjectedToolCallId
from langgraph.prebuilt import InjectedState
from langgraph.graph import StateGraph, START, MessagesState, END
from langgraph.types import Command
# 自定义创建交接工具的函数
def create_handoff_tool(*, agent_name: str, description: str | None = None):
name = f"transfer_to_{agent_name}" # 工具名称格式
description = description or f"Ask {agent_name} for help." # 默认描述
@tool(name, description=description)
def handoff_tool(
state: Annotated[MessagesState, InjectedState], # 注入当前状态
tool_call_id: Annotated[str, InjectedToolCallId], # 注入工具调用ID
) -> Command:
# 创建工具消息(指示交接成功)
tool_message = {
"role": "tool",
"content": f"Successfully transferred to {agent_name}", # 成功消息
"name": name,
"tool_call_id": tool_call_id,
}
# 返回命令:跳转到目标智能体节点,更新状态(添加工具消息),并指定在父图中执行跳转
return Command(
goto=agent_name, # 目标节点名称
update={state, "messages": state["messages"] + [tool_message]}, # 更新状态(添加工具消息)
graph=Command.PARENT, # 在父图中执行跳转
)
return handoff_tool
# 使用自定义函数创建研究智能体的交接工具
assign_to_research_agent = create_handoff_tool(
agent_name="research_agent",
description="Assign task to a researcher agent.", # 自定义描述
)
# 使用自定义函数创建数学智能体的交接工具
assign_to_math_agent = create_handoff_tool(
agent_name="math_agent",
description="Assign task to a math agent.", # 自定义描述
)
# 创建监督者智能体,使用自定义的交接工具
supervisor_agent = create_react_agent(
model="openai:gpt-4o-mini", # 使用的模型
tools=[assign_to_research_agent, assign_to_math_agent], # 使用自定义工具
prompt=(
"你是一个监督者,管理着两个智能体:\n"
"- 一个研究智能体。将研究相关任务分配给这个智能体\n"
"- 一个数学智能体。将数学相关任务分配给这个智能体\n"
"一次只分配给一个智能体工作,不要并行调用智能体。\n"
"你自己不要执行任何工作。"
),
name="supervisor", # 智能体名称
)
# 定义多智能体监督者图
supervisor = (
StateGraph(MessagesState) # 使用消息状态图
# 添加监督者节点 (destinations 仅用于可视化,不影响运行时行为)
.add_node(supervisor_agent, destinations=("research_agent", "math_agent", END))
.add_node(research_agent) # 添加研究智能体节点
.add_node(math_agent) # 添加数学智能体节点
.add_edge(START, "supervisor") # 起始边:START -> supervisor
# 定义返回边:智能体完成任务后总是返回监督者
.add_edge("research_agent", "supervisor")
.add_edge("math_agent", "supervisor")
.compile() # 编译图
)
# (可选) 显示图结构
display(Image(supervisor.get_graph().draw_mermaid_png()))
```
输出示例 (运行查询):
```python
# 使用编译好的监督者图处理查询
for chunk in supervisor.stream(
{
"messages": [
{
"role": "user",
"content": "find US and New York state GDP in 2024. what % of US GDP was New York state?",
}
]
},
):
pretty_print_messages(chunk, last_message=True) # 美化打印每个更新块的最后一条消息
# 获取最终的消息历史
final_message_history = chunk["supervisor"]["messages"] # 最终状态中的消息历史
```
Update from node supervisor:
================================= Tool Message =================================
Name: transfer_to_research_agent
Successfully transferred to research_agent
Update from node research_agent:
================================== Ai Message ==================================
Name: research_agent
- US GDP in 2024: Approximately $28.18 trillion USD (Statista).
- New York State GDP in 2024: The specific GDP number for New York State in 2024 has not been directly located, but relevant forecasts are provided in the state assembly reports.
For calculations regarding the percentage of the US GDP that New York State comprises, specific figures would need to be sourced.
Update from node supervisor:
================================= Tool Message =================================
Name: transfer_to_math_agent
Successfully transferred to math_agent
Update from node math_agent:
================================== Ai Message ==================================
Name: math_agent
5.93%
Update from node supervisor:
================================== Ai Message ==================================
Name: supervisor
In 2024, the approximate GDP of the United States is $28.18 trillion USD. New York State's GDP is estimated to be around $1.671 trillion USD. Therefore, New York State contributes about 5.93% of the total US GDP.
上面已经实现了 final_message_history .现在需要检查一下完整的结果消息历史:
for message in final_message_history:
message.pretty_print()
输出:
================================ Human Message =================================
find US and New York state GDP in 2024. what % of US GDP was New York state?
================================== Ai Message ==================================
Name: supervisor
Tool Calls:
transfer_to_research_agent (call_9Innk7roc0BYXdvTnvljH267)
Call ID: call_9Innk7roc0BYXdvTnvljH267
Args:
================================= Tool Message =================================
Name: transfer_to_research_agent
Successfully transferred to research_agent
================================== Ai Message ==================================
Name: research_agent
Tool Calls:
tavily_search_results_json (call_6rXCVDfY6Rg9FiWHsxbyBxQG)
Call ID: call_6rXCVDfY6Rg9FiWHsxbyBxQG
Args:
query: US GDP 2024 forecast
tavily_search_results_json (call_hAsCKkl3tMIFwixTTp7eh0zt)
Call ID: call_hAsCKkl3tMIFwixTTp7eh0zt
Args:
query: New York state GDP 2024 forecast
================================= Tool Message =================================
Name: tavily_search_results_json
[{"title": "GDP forecast U.S. 2034 - Statista", "url": "https://www.statista.com/statistics/216985/forecast-of-us-gross-domestic-product/", "content": "[](https://www.statista.com/statistics/216985/forecast-of-us-gross-domestic-product/#statisticContainer) This graph shows a forecast of the gross domestic product of the United States of America for fiscal years 2024 to 2034. GDP refers to the market value of all final goods and services produced within a country in a given period. According to the CBO, the United States GDP will increase steadily over the next decade from 28.18 trillion U.S. dollars in 2023 to 41.65 trillion U.S. dollars in [...] * [Economy & Politics](https://www.statista.com/markets/2535/economy-politics/)›\n* [Economy](https://www.statista.com/markets/2535/topic/970/economy/)\n\nU.S. GDP forecast 2024-2034\n===========================\n\n Published by \n\n[Abigail Tierney](https://www.statista.com/aboutus/our-research-commitment/3508/abigail-tierney), \n\n Jul 5, 2024 [...] .%20dollars)%C2%A0https://www.statista.com/statistics/216985/forecast-of-us-gross-domestic-product/)[](mailto:?subject=Statista%C2%A0-%C2%A0Forecast%20of%20the%20gross%20domestic%20product%20of%20the%20United%20States%20from%20fiscal%20year%202024%20%20to%20fiscal%20year%202034%20(in%20billion%20U.S.%20dollars)&body=This%20graph%20shows%20a%20forecast%20of%20the%20gross%20domestic%20product%20of%20the%20United%20States%20of%20America%20for%20fiscal%20years%202024%20to%202034", "score": 0.9245858}, {"title": "United States GDP Growth Rate - Trading Economics", "url": "https://tradingeconomics.com/united-states/gdp-growth", "content": "| [GDP from Services](https://tradingeconomics.com/united-states/gdp-from-services) | 17050.50 | 16949.30 | USD Billion | Dec 2024 |\n| [GDP from Transport](https://tradingeconomics.com/united-states/gdp-from-transport) | 730.50 | 721.40 | USD Billion | Dec 2024 |\n| [GDP from Utilities](https://tradingeconomics.com/united-states/gdp-from-utilities) | 350.80 | 341.40 | USD Billion | Dec 2024 | [...] | [GDP from Manufacturing](https://tradingeconomics.com/united-states/gdp-from-manufacturing) | 2406.80 | 2402.80 | USD Billion | Dec 2024 |\n| [GDP from Mining](https://tradingeconomics.com/united-states/gdp-from-mining) | 343.60 | 337.60 | USD Billion | Dec 2024 |\n| [GDP from Public Administration](https://tradingeconomics.com/united-states/gdp-from-public-administration) | 2653.10 | 2635.50 | USD Billion | Dec 2024 | [...] | [Gross Fixed Capital Formation](https://tradingeconomics.com/united-states/gross-fixed-capital-formation) | 4346.50 | 4265.90 | USD Billion | Mar 2025 |\n| [Gross National Product](https://tradingeconomics.com/united-states/gross-national-product) | 23620.90 | 23427.70 | USD Billion | Dec 2024 |\n| [Real Consumer Spending](https://tradingeconomics.com/united-states/real-consumer-spending) | 1.20 | 4.00 | percent | Mar 2025 |", "score": 0.8458536}, {"title": "A post-cycle economy faces greater policy uncertainty", "url": "https://am.jpmorgan.com/us/en/asset-management/adv/insights/market-insights/investment-outlook/us-economic-outlook/", "content": "This year, the economy saw surprisingly robust growth with real GDP on track to expand at a 1.8% annualized rate in the fourth quarter, closing 2024 with 2.3% annual growth, by our estimates. The biggest driver of this strength has been consumer spending, which contributed an average 78% of real GDP growth in the first three quarters. Despite pushing back on high retail prices, a thriftier consumer managed to stretch their budget and still expand their shopping cart. Inflation-adjusted consumer", "score": 0.83290404}]
================================= Tool Message =================================
Name: tavily_search_results_json
[{"title": "Annual State of the City's Economy and Finances 2024", "url": "https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/", "content": "[[1]](https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/#_ftnref1) At that time, the Comptroller’s Office expected five-year cumulative real GDP growth, 2020 to 2024, of 8.7 percent while the mayor expected 9.5 percent.\n\n[[2]](https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/#_ftnref2) U.S. Bureau of Labor Statistics Local Area Unemployment Statistics (LAUS). [...] Nationally, the economy is expected to grow by 2.3 percent in 2025, stronger than the 1.6 percent that was last forecast in May, according to the Office of the New York City Comptroller’s forecast. Short-term interest rates are projected to decline more rapidly over the next few years, reaching 3 percent by early 2026, while inflation remains near targeted levels. Average wages and overall employment levels in New York City are estimated to have been stronger than had been forecast in 2024. The [...] (constant 2019 dollars)22,550 15,322 13,596 19,451 21,211 21,096\n_% change_(32.1%)(11.3%)43.1%9.0%(0.5%)\n\nSource: NY State Department of Taxation and Finance and Office of the New York City Comptroller", "score": 0.882276}, {"title": "New York by the Numbers Monthly Economic and Fiscal Outlook", "url": "https://comptroller.nyc.gov/newsroom/newsletter/new-york-by-the-numbers-monthly-economic-and-fiscal-outlook-no-101-may-2025/", "content": "| A | Current (2024-25) | Year Earlier (2023-24) | Pre-Pandemic* | E |\n| --- | --- | --- | --- | --- |\n| Jan-24 | 1,335 | 1,810 | 1,307 | |\n| Feb-24 | 1,937 | 1,292 | 1,316 | |\n| Mar-24 | 1,641 | 1,232 | 884 | |\n| Apr-24 | 1,360 | 929 | 947 | |\n| May-24 | 652 | 1,377 | 1,020 | |\n| Jun-24 | 665 | 1,200 | 1,265 | |\n| Jul-24 | 529 | 905 | 1,232 | |\n| Aug-24 | 516 | 754 | 935 | |\n| Sep-24 | 355 | 805 | 806 | |\n| Oct-24 | 375 | 844 | 1,026 | |\n| Nov-24 | 431 | 801 | 1,476 | | [...] | 26-Oct-24 | 5.30% | 12.50% |\n| 2-Nov-24 | 9.40% | 6.90% |\n| 9-Nov-24 | 3.40% | 0.30% |\n| 16-Nov-24 | 6.50% | -1.00% |\n| 23-Nov-24 | 5.20% | -1.20% |\n| 30-Nov-24 | -2.90% | -1.10% |\n| 7-Dec-24 | 3.30% | 5.00% |\n| 14-Dec-24 | 3.50% | 6.20% |\n| 21-Dec-24 | -1.80% | 6.70% |\n| 28-Dec-24 | 2.60% | 7.30% |\n| 4-Jan-25 | -5.00% | 2.90% |\n| 11-Jan-25 | -4.90% | 4.70% |\n| 18-Jan-25 | -2.90% | 5.60% |\n| 25-Jan-25 | -5.60% | 2.40% |\n| 1-Feb-25 | -4.60% | 2.40% |\n| 8-Feb-25 | -5.60% | -0.70% | [...] | 6-Jul-24 | -16.10% | -5.40% |\n| 13-Jul-24 | -14.80% | -1.10% |\n| 20-Jul-24 | -11.70% | 0.60% |\n| 27-Jul-24 | -12.40% | 4.40% |\n| 3-Aug-24 | -5.90% | 4.00% |\n| 10-Aug-24 | -2.50% | 0.90% |\n| 17-Aug-24 | -2.80% | -0.50% |\n| 24-Aug-24 | -0.60% | -2.60% |\n| 31-Aug-24 | 0.30% | 0.30% |\n| 7-Sep-24 | 0.70% | 2.80% |\n| 14-Sep-24 | 1.40% | 5.20% |\n| 21-Sep-24 | 2.00% | 6.60% |\n| 28-Sep-24 | 2.70% | 7.30% |\n| 5-Oct-24 | -0.50% | 12.10% |\n| 12-Oct-24 | 4.20% | 14.70% |\n| 19-Oct-24 | 0.10% | 14.80% |", "score": 0.8576849}]
================================== Ai Message ==================================
Name: research_agent
Tool Calls:
tavily_search_results_json (call_WwAmuE7MF6MvQRUPZ7SrBaT3)
Call ID: call_WwAmuE7MF6MvQRUPZ7SrBaT3
Args:
query: New York state GDP 2024 forecast in dollars
================================= Tool Message =================================
Name: tavily_search_results_json
[{"title": "[PDF] New York State Economic and Revenue Report", "url": "https://nyassembly.gov/Reports/WAM/2025economic_revenue/2025_report.pdf?v=1740533306", "content": "New York State Economic Outlook (Percent Change) Actual Estimate Forecast Forecast 2023-24 2024-25 2025-26 2026-27 Employment Percent Change 1.8 1.5 1.0 0.8 Level (Thousands) 9,441.6 9,589.7 9,694.3 9,773.6 Personal Income Percent Change 5.2 5.8 4.6 4.4 Level (Billions) 1,581.5 1,671.1 1,754.9 1,835.0 Total Wages Percent Change 4.2 6.7 4.4 4.0 Level (Billions) 864.0 915.9 964.3 1,005.1 Base Wages Percent Change 5.1 5.4 4.4 4.3 Level (Billions) 764.0 803.1 840.7 876.6 Variable Compensation [...] Sources: Federal Reserve; NYS Assembly Ways and Means Committee staff. NYS ASSEMBLY| U.S. ECONOMIC FORECAST AT A GLANCE| 15 Actual Actual Actual Forecast Forecast 2022 2023 2024 2025 2026 Real GDP 2.5 2.9 2.8 2.4 2.1 Consumption 3.0 2.5 2.8 2.7 2.1 Investment 6.0 0.1 4.0 3.1 3.8 Exports 7.5 2.8 3.2 2.4 1.1 Imports 8.6 (1.2) 5.4 3.5 1.3 Government (1.1) 3.9 3.4 1.5 0.1 Federal (3.2) 2.9 2.5 1.7 0.2 State and Local 0.2 4.4 3.9 1.4 0.1 Personal Income 3.1 5.9 5.5 5.0 4.9 Wages & Salaries 7.8 5.4 [...] three-month moving average of 2.5 million in December 2023 to 872,000 in December 2024. The ratio of job openings to unemployed persons, another key metric for assessing the balance between labor demand and supply, has also steadily declined in recent months. By December 2024, this ratio had dropped to 1.10, down from its peak of 2.03 in March 2022. 24 | U.S. ECONOMIC FORECAST ANALYSIS | NYS ASSEMBLY With diminishing supply shortages in the labor market, growth of labor and other incomes will", "score": 0.83290404}, {"title": "Annual State of the City's Economy and Finances 2024", "url": "https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/", "content": "(constant 2019 dollars)22,550 15,322 13,596 19,451 21,211 21,096\n_% change_(32.1%)(11.3%)43.1%9.0%(0.5%)\n\nSource: NY State Department of Taxation and Finance and Office of the New York City Comptroller [...] [[1]](https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/#_ftnref1) At that time, the Comptroller’s Office expected five-year cumulative real GDP growth, 2020 to 2024, of 8.7 percent while the mayor expected 9.5 percent.\n\n[[2]](https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/#_ftnref2) U.S. Bureau of Labor Statistics Local Area Unemployment Statistics (LAUS). [...] | Retail Trade | 301,565 | $56,208 | 14.4 | (0.6) | (5.2) | 2.7 | 2.9 | 2.2 | 2.1 |\n| Leisure & Hospitality | 431,227 | $56,086 | 96.2 | 32.4 | 15.4 | 8.9 | 3.8 | 4.5 | 7.3 |\n| Total: Low Wage Sectors | 1,997,491 | $62,185 | 184.6 | 102.2 | 91.6 | 62.7 | 32.0 | 26.8 | 29.3 |\n| Total NYC Employment | 4,485,695 | $114,294 | 307.7 | 119.9 | 78.1 | 88.0 | 65.1 | 53.2 | 51.4 |", "score": 0.81979275}]
================================== Ai Message ==================================
Name: research_agent
- US GDP in 2024: Approximately $28.18 trillion USD (Statista).
- New York State GDP in 2024: The specific GDP number for New York State in 2024 has not been directly located, but relevant forecasts are provided in the state assembly reports.
For calculations regarding the percentage of the US GDP that New York State comprises, specific figures would need to be sourced.
================================== Ai Message ==================================
Name: supervisor
Tool Calls:
transfer_to_math_agent (call_oaEpCKr9zw496FBNjBB5dujp)
Call ID: call_oaEpCKr9zw496FBNjBB5dujp
Args:
================================= Tool Message =================================
Name: transfer_to_math_agent
Successfully transferred to math_agent
================================== Ai Message ==================================
Name: math_agent
Tool Calls:
divide (call_e6ZYc9SkjuKzEZjhBo2C77P2)
Call ID: call_e6ZYc9SkjuKzEZjhBo2C77P2
Args:
a: 1.6711
b: 28.18
================================= Tool Message =================================
Name: divide
0.05930092264017033
================================== Ai Message ==================================
Name: math_agent
Tool Calls:
multiply (call_j3rCjTQ5AGqobs2UTXXTT07w)
Call ID: call_j3rCjTQ5AGqobs2UTXXTT07w
Args:
a: 0.05930092264017033
b: 100
================================= Tool Message =================================
Name: multiply
5.930092264017033
================================== Ai Message ==================================
Name: math_agent
5.93%
================================== Ai Message ==================================
Name: supervisor
In 2024, the approximate GDP of the United States is $28.18 trillion USD. New York State's GDP is estimated to be around $1.671 trillion USD. Therefore, New York State contributes about 5.93% of the total US GDP.
4.4 消息转发功能
你可以给监督者配个小工具,用`create_forward_message_tool`方法把某个工作Agent的最后回复直接推送到最终输出结果里。当监督者觉得某个Agent的回复已经很完整,不需要再加工或总结时特别管用。这样既省监督者的计算资源,又能避免二次转述把原意带跑偏。
```python
from langgraph_supervisor.handoff import create_forward_message_tool
# 假设 research_agent 和 math_agent 已按之前方式定义
forwarding_tool = create_forward_message_tool("supervisor") # 参数指定转发消息的署名
workflow = create_supervisor(
[research_agent, math_agent],
model=model,
# 把转发工具和其他交接工具一起传进去
tools=[forwarding_tool]
)
```
这样就创建了个叫`forward_message`的工具,监督者调用时需要传个`from_agent`参数,指明要转发哪个Agent的消息。
5. 群体协作模式实战
下面是使用`langgraph_swarm`库实现群体协作的代码(该库基于LangGraph),让不同Agent能动态协作和交接任务。我们用和监督者模式相同的数学Agent和研究Agent来演示:
```python
from langchain_openai import ChatOpenAI
from langgraph.graph import START, END
from langchain_community.tools.tavily_search import TavilySearchResults
from langgraph.prebuilt import create_react_agent
from langgraph_swarm import create_swarm, create_handoff_tool
from IPython.display import Image, display
import os
# 选个语言模型
model = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY"))
# 定义工具函数
def add(a: float, b: float) -> float:
"""两数相加"""
return a + b
def multiply(a: float, b: float):
"""两数相乘"""
return a * b
def divide(a: float, b: float):
"""两数相除"""
return a / b
# 群体协作专属交接工具
handoff_to_research_agent = create_handoff_tool(
agent_name="research_agent",
description="把控制权转给研究Agent处理搜索任务/资料收集"
)
handoff_to_math_agent = create_handoff_tool(
agent_name="math_agent",
description="把控制权转给数学Agent处理计算问题"
)
tavily_api_key = os.getenv("TAVILY_API_KEY", "你的tavily密钥")
web_search = TavilySearchResults(max_results=3, tavily_api_key=tavily_api_key)
# 创建工作Agent
research_agent = create_react_agent(
model=model,
tools=[web_search, handoff_to_math_agent],
name="research_agent",
prompt=(
"你是专门搞网络搜索的情报员\n\n"
"行动指南:\n"
"- 只管查资料/做调研/收集信息\n"
"- 碰到数学题立刻甩锅给handoff_to_math_agent()\n"
"- 干完活要交完整调研报告\n"
"- 需要算数时调用handoff_to_math_agent()"
)
)
math_agent = create_react_agent(
model=model,
tools=[add, multiply, divide, handoff_to_research_agent],
name="math_agent",
prompt=(
"你是专注解题的数学小能手\n\n"
"行动指南:\n"
"- 只管算数/解方程/分析数据\n"
"- 碰到查资料需求立刻甩锅给handoff_to_research_agent()\n"
"- 算完题要写清楚步骤和答案\n"
"- 需要查资料时调用handoff_to_research_agent()"
)
)
swarm_agent = create_swarm(
agents=[research_agent, math_agent],
default_active_agent="math_agent",
).compile()
display(Image(swarm_agent.get_graph().draw_mermaid_png()))
```
测试流程代码
```python
def test_swarm_functionality():
"""测试群体协作功能:通过GDP查询验证任务交接机制"""
print(f"查询:查找2024年美国及纽约州GDP,纽约州GDP占全美比例是多少?")
print("-" * 80)
try:
for chunk in swarm_agent.stream(
{
"messages": [
{
"role": "user",
"content": "find US and New York state GDP in 2024. what % of US GDP was New York state?",
}
]
},
subgraphs=False
):
pretty_print_messages(chunk, last_message=True)
print(f"测试成功完成")
except Exception as e:
print(f"测试失败,错误信息:{str(e)}")
print("=" * 80)
# 执行测试
if __name__ == "__main__" or True:
test_swarm_functionality()
```
测试输出结果
```
查询:查找2024年美国及纽约州GDP,纽约州GDP占全美比例是多少?
--------------------------------------------------------------------------------
来自 math_agent 节点的更新:
================================= 工具消息 =================================
名称:transfer_to_research_agent
成功转交给 research_agent
来自 research_agent 节点的更新:
================================= 工具消息 =================================
名称:transfer_to_math_agent
成功转交给 math_agent
来自 math_agent 节点的更新:
================================== AI消息 ==================================
名称:math_agent
### 计算结果:
- 2024年美国GDP: 约 28.18万亿美元
- 2024年纽约州GDP: 约 2.29万亿美元
- 纽约州GDP占全美比例: 约 8.13%
这意味着2024年纽约州预计将贡献美国GDP总量的8.13%
测试成功完成
================================================================================
```
6. 运行智能体
6.1 调用模式
代理支持两种运行方式:
同步模式:用`.invoke()`或`.stream()`——调用方(用户/系统)必须等代理完成任务才能继续操作
异步模式:用`await .ainvoke()`或`async for .astream()`——代理收到请求后开始处理,调用方无需等待可继续其他任务,结果通过回调/通知返回
同步调用示例
```python
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(...)
response = agent.invoke({"messages": [{"role": "user", "content": "旧金山天气怎么样"}]})
```
异步调用示例
```python
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(...)
response = await agent.ainvoke({"messages": [{"role": "user", "content": "旧金山天气怎么样"}]})
```
6.2 输入格式
代理输入必须是包含`messages`键的字典:
`messages`键值要求:消息对象列表
可通过额外字段实现动态行为(如运行时数据传递)
📌 特别注意:
纯字符串输入会自动转成`HumanMessage`(人类消息)
但`create_react_agent`的`prompt`参数是字符串时会被视作`SystemMessage`(系统消息)
6.3 输出格式
代理输出始终是字典结构,包含:
`messages`键:完整交互记录(用户输入/助理回复/工具调用)
(可选)`structured_response`键:启用结构化输出时存在
自定义状态字段:若配置了`state_schema`,则包含工具执行更新的状态值
```python
# 典型输出示例
{
"messages": [
{"role": "user", "content": "旧金山天气"},
{"role": "tool", "name": "weather_api", "content": "..."},
{"role": "assistant", "content": "当前气温22℃"}
],
"structured_response": { # 可选字段
"location": "旧金山",
"temperature": 22,
"unit": "℃"
}
}
```
6.4 流式输出
代理支持流式响应,提升交互实时性,包含以下内容:
每步执行后的进度更新
LLM词元实时生成过程
执行过程中的自定义工具消息
流式模式支持同步/异步两种方式:
同步流式调用
```python
for chunk in agent.stream(
{"messages": [{"role": "user", "content": "旧金山天气怎么样"}]},
stream_mode="updates" # 实时获取增量更新
):
print(chunk) # 打印每次状态变化
```
(前文示例均采用此模式)
异步流式调用
```python
async for chunk in agent.astream(
{"messages": [{"role": "user", "content": "旧金山天气怎么样"}]},
stream_mode="updates"
):
print(chunk) # 异步处理每次更新
```
6.5 最大迭代次数
限制代理执行步数,防止无限循环。可通过两种方式配置:
运行时配置
```python
from langgraph.errors import GraphRecursionError
max_iterations = 3 # 最大迭代3次
recursion_limit = 2 * max_iterations + 1 # 计算安全阈值
try:
response = agent.invoke(
{"messages": [{"role": "user", "content": "旧金山天气"}]},
{"recursion_limit": recursion_limit}, # 传入配置
)
except GraphRecursionError: # 捕获超限异常
print("代理因迭代次数超限停止")
```
代理初始化配置
```python
agent_with_recursion_limit = agent.with_config(
recursion_limit=recursion_limit # 绑定迭代限制
)
try:
response = agent_with_recursion_limit.invoke(
{"messages": [{"role": "user", "content": "旧金山天气"}]}
)
except GraphRecursionError:
print("代理因迭代次数超限停止")
```
7. 隐藏的障碍
多智能体协同面临的三大核心挑战:
研究人员分析150+任务和6位专家意见,归纳出14类故障模式
1. 系统设计缺陷
任务定义模糊不清
架构设计存在漏洞
资源分配机制不合理
2. 智能体协作失调
跨智能体通信故障
任务优先级冲突
数据格式不兼容
3. 任务验证失效
结果校验机制缺失
错误终止条件设定
异常处理流程漏洞
8. 突破壁垒
为应对这些挑战,研究者提出两大核心解决方案:
1.智能体角色定义精细化
通过明确职责边界消除任务重叠与理解歧义,例如:
禁止数学代理执行网络搜索
限制研究代理进行数值计算
2. 强化协同编排机制
建立高效协调策略优化任务流转:
制定跨代理通信协议
设计任务优先级仲裁规则
实现数据格式标准化
行业协议突破
Anthropic的MCP协议
作为首个AI系统集成开放标准,MCP通过三层架构破除工具壁垒:
MCP客户端:内置于代理的标准化请求构造器
MCP服务器:连接数据库/API的核心枢纽
JSON-RPC通道:实现双向实时数据交换
Google的A2A协议
Google 在2025年4月发布的创新性方案,聚焦智能体间协作:
智能体卡片(Agent Cards):JSON格式公开能力说明(如"支持实时交通分析")
任务生命周期管理:追踪长时任务进度状态
多模态通信:兼容文本/图像/数据流传输
协同运作范式
比方说在处理"区域经济预测"任务时:
规划智能体经A2A指派研究代理采集数据
研究智能体通过MCP调用统计局API
分析智能体经MCP启动Python建模引擎
呈现智能体生成最终可视化报告
💡 协议定位差异
A2A协议 = 建筑师间的蓝图协作(智能体横向联动)
MCP协议 = 工人使用电动工具(智能体垂直接入资源)
这种分层协作范式已获产业验证:Block公司采用MCP+A2A构建的代理系统,使财务流程效率提升300%,错误率下降85%。当前微软正将MCP深度集成至Windows系统,预示操作系统将进化为基础代理平台。
9. 开发可扩展AI智能体的路线图
1. 模型选择
挑选大语言模型(LLM)需满足:
擅长逻辑推理与思维处理
支持分步思考(思维链模式)
输出结果稳定可靠
技巧:从Llama、Claude Opus或Mistral入手(开源模型提供更高定制自由度)
2. 设计代理推理流程
明确代理的任务处理方式:
是否需要思考停顿再回应?
采取分步规划还是立即执行?
何时调用外部工具辅助?
技巧:初始阶段采用ReAct框架或"先规划后执行"策略
3. 设定操作规范
建立清晰的交互规则:
定义应答行为与语气风格
明确外部工具调用条件
统一响应格式(如JSON/Markdown)
技巧:将其视为代理的内部操作协议
4. 记忆机制集成
弥补LLM的长期记忆缺陷:
采用滑动窗口记忆保留近期上下文
总结历史对话要点
持久化关键信息(用户偏好/决策记录)
技巧:通过MemGPT或ZepAI简化记忆管理
5. 工具与API集成
赋能代理执行实际任务:
获取外部实时数据
更新CRM系统及数据库
执行计算与数据转换
技巧:运用MCP协议实现工具无缝接入
6. 明确任务目标
为代理设定具体指令:
✅ 合格示例:"汇总用户反馈并提出改进建议"
❌ 无效示例:"要能帮忙"
技巧:聚焦任务范围——明确定义"禁止事项"比开放指令更高效
7. 扩展多智能体团队
组建专业化协作团队:
情报代理:负责信息收集
分析代理:执行数据解析
呈现代理:格式化输出结果
技巧:明确分工的专职代理可大幅提升系统效能
10. 结语
您已掌握构建可扩展AI代理的全链路知识——从基础设计到突破隐形壁垒!现在是时候付诸实践:
选择核心模型:轻量快捷型 or 复杂稳健型?
架构决策:监督员模式 or 群蜂模式更能提升效能?
调用模式:异步处理是否为您的场景解锁新可能?
通往可扩展智能体的路线图已在你手中,但挑战犹存:
预见哪些设计/实施壁垒?
如何定制任务交接工具?
怎样调整迭代策略?
延伸阅读: