神译局是36氪旗下编译团队,关注科技、商业、职场、生活等领域,重点介绍国外的新技术、新观点、新风向。
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],
)
随着所需工具数量的增加,可以考虑将任务拆分给多个智能体。
```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()))
```
```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 = s[-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%。
测试成功完成
================================================================================
```
```python
supervisor = create_supervisor(
agents=[agent1, agent2],
output_mode="full_history" # 输出模式:完整历史
)
```
```python
supervisor = create_supervisor(
agents=[agent1, agent2],
output_mode="last_message" # 输出模式:仅最后一条消息
)
```
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")
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,
)
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.
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 strengthhas 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_e6ZYc9SkjuKzEZjhBoC77P2
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.
```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]
)
```
```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%
测试成功完成
================================================================================
```
```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": "旧金山天气怎么样"}]})
```
```python
# 典型输出示例
{
"messages": [
{"role": "user", "content": "旧金山天气"},
"role": "tool", "name": "weather_api", "content": "..."},
{"role": "assistant", "content": "当前气温22℃"}
],
"structured_response": { # 可选字段
"location": "旧金山",
"temperature": 22,
"unit": "℃"
}
}
```
```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) # 异步处理每次更新
```
```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("代理因迭代次数超限停止")
```
通信人家园 (https://www.txrjy.com/) | Powered by C114 |