建立專門的研究和數學代理人 使用預建的langgraph-supervisor來構建一個協調它們的監督者 從頭開始建立一個監督者 實施高級任務委派 pip install -U langgraph langgraph-supervisor langchain-tavily "langchain[openai]" import getpass import os def _set_if_undefined(var: str): if not os.environ.get(var): os.environ[var] = getpass.getpass(f"Please provide your {var}") _set_if_undefined("OPENAI_API_KEY") _set_if_undefined("TAVILY_API_KEY") 1.建立工作代理 研究代理將能夠使用 Tavily API 訪問網路搜尋工具 數學代理將可以使用簡單的數學工具(add,multiply,divide) Research agent¶ 研究代理 from langchain_tavily import TavilySearch web_search = TavilySearch(max_results=3) web_search_results = web_search.invoke("who is the mayor of NYC?") print(web_search_results["results"][0]["content"]) 要創建個別的工作代理,我們將使用 LangGraph 的預建代理。 from langgraph.prebuilt import create_react_agent research_agent = create_react_agent( model="openai:gpt-4.1", tools=[web_search], prompt=( "你是專業的研究助理代理人。\n\n" "【工作職責】\n" "1. 執行研究相關任務:\n" " - 信息檢索與收集\n" " - 資料分析與整理\n" " - 內容查證與驗證\n\n" "2. 工作限制:\n" " - 不處理數學計算任務\n" " - 不執行非研究類工作\n" " - 專注於使用提供的研究工具\n\n" "【回報要求】\n" "- 任務完成後直接向主管回報\n" "- 僅提供研究成果,不添加額外解釋\n" "- 保持回應專業、準確、簡潔" ), name="research_agent", ) 讓我們運行代理以驗證其行為是否如預期。 for chunk in research_agent.stream( {"messages": [{"role": "user", "content": "who is the mayor of NYC?"}]} ): pretty_print_messages(chunk) Update from node agent: ================================== Ai Message ================================== Name: research_agent Tool Calls: tavily_search (call_T4wrj7DKAG5hVtNVhjRYGdei) Call ID: call_T4wrj7DKAG5hVtNVhjRYGdei Args: query: current mayor of New York City Update from node tools: ================================= Tool Message ================================= Name: tavily_search {"query": "current mayor of New York City", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "List of mayors of New York City - Wikipedia", "url": "https://en.wikipedia.org/wiki/List_of_mayors_of_New_York_City", "content": "The mayor of New York City is the chief executive of the Government of New York City, as stipulated by New York City's charter.The current officeholder, the 110th in the sequence of regular mayors, is Eric Adams, a member of the Democratic Party.. During the Dutch colonial period from 1624 to 1664, New Amsterdam was governed by the Director of New Netherland.", "score": 0.9039154, "raw_content": null}, {"title": "Office of the Mayor | Mayor's Bio | City of New York - NYC.gov", "url": "https://www.nyc.gov/office-of-the-mayor/bio.page", "content": "Mayor Eric Adams has served the people of New York City as an NYPD officer, State Senator, Brooklyn Borough President, and now as the 110th Mayor of the City of New York. He gave voice to a diverse coalition of working families in all five boroughs and is leading the fight to bring back New York City's economy, reduce inequality, improve", "score": 0.8405867, "raw_content": null}, {"title": "Eric Adams - Wikipedia", "url": "https://en.wikipedia.org/wiki/Eric_Adams", "content": "Eric Leroy Adams (born September 1, 1960) is an American politician and former police officer who has served as the 110th mayor of New York City since 2022. Adams was an officer in the New York City Transit Police and then the New York City Police Department (NYPD) for more than 20 years, retiring at the rank of captain.He served in the New York State Senate from 2006 to 2013, representing the", "score": 0.77731717, "raw_content": null}], "response_time": 1.31} Update from node agent: ================================== Ai Message ================================== Name: research_agent The current mayor of New York City is Eric Adams. Math agent def add(a: float, b: float): """將兩個數字相加 參數: a: 第一個數字 b: 第二個數字 返回: 兩數之和 """ return a + b def multiply(a: float, b: float): """將兩個數字相乘 參數: a: 第一個數字 b: 第二個數字 返回: 兩數之積 """ return a * b def divide(a: float, b: float): """將兩個數字相除 參數: a: 被除數 b: 除數 返回: 商值,如果除數為零則返回錯誤信息 """ if b == 0: return "錯誤:除數不能為零" return a / b math_agent = create_react_agent( model="openai:gpt-4.1", tools=[add, multiply, divide], prompt=( "你是數學計算專家代理。\n\n" "【工作職責】\n" "1. 數學運算:\n" " - 基礎算術運算(加、乘、除)\n" " - 精確計算數值\n" " - 處理數學相關查詢\n\n" "2. 工作限制:\n" " - 只處理數學計算任務\n" " - 不處理非數學相關工作\n" " - 專注使用提供的計算工具\n\n" "【回報要求】\n" "- 計算完成後直接回報主管\n" "- 僅提供計算結果\n" "- 不附加說明文字\n" "- 確保結果準確簡潔" ), name="math_agent", ) 讓我們運行數學代理: for chunk in math_agent.stream( {"messages": [{"role": "user", "content": "what's (3 + 5) x 7"}]} ): pretty_print_messages(chunk) Update from node agent: ================================== Ai Message ================================== Name: math_agent Tool Calls: add (call_LqyOrR1Ktr2LVLDlXpbWNAsp) Call ID: call_LqyOrR1Ktr2LVLDlXpbWNAsp Args: a: 3 b: 5 Update from node tools: ================================= Tool Message ================================= Name: add 8.0 Update from node agent: ================================== Ai Message ================================== Name: math_agent Tool Calls: multiply (call_IBXYtlEMdZrfDZ8g8bWC31pM) Call ID: call_IBXYtlEMdZrfDZ8g8bWC31pM Args: a: 8 b: 7 Update from node tools: ================================= Tool Message ================================= Name: multiply 56.0 Update from node agent: ================================== Ai Message ================================== Name: math_agent 56 2. 使用 langgraph-supervisor 建立監督者 from langgraph_supervisor import create_supervisor from langchain.chat_models import init_chat_model supervisor = create_supervisor( model=init_chat_model("openai:gpt-4.1"), agents=[research_agent, math_agent], prompt=( "你是專案經理,負責協調和管理專業團隊。\n\n" "【團隊架構】\n" "研究部門代理:\n" "• 職責:資訊研究、市場分析、數據收集\n" "• 適用:需要搜索、調查、分析的任務\n\n" "計算部門代理:\n" "• 職責:數學運算、數值計算、公式處理\n" "• 適用:需要計算、運算、數學分析的任務\n\n" "【管理準則】\n" "1. 任務分配:\n" " - 仔細分析任務需求\n" " - 選擇最適合的代理執行\n" " - 確保任務分配準確無誤\n\n" "2. 執行原則:\n" " - 串行執行,不並行調用\n" " - 監督但不干預執行過程\n" " - 專注於管理協調工作\n\n" "3. 目標導向:\n" " - 確保任務高效完成\n" " - 維護團隊協作順暢\n" " - 提供最佳解決方案" ), add_handoff_back_messages=True, output_mode="full_history", ).compile() from IPython.display import display, Image display(Image(supervisor.get_graph().draw_mermaid_png())) 研究代理將查找必要的 GDP 信息 數學代理將執行除法以找出紐約州 GDP 的百分比,根據要求 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: ================================= Tool Message ================================= Name: transfer_back_to_supervisor Successfully transferred back to supervisor Update from node supervisor: ================================= Tool Message ================================= Name: transfer_to_math_agent Successfully transferred to math_agent Update from node math_agent: ================================= Tool Message ================================= Name: transfer_back_to_supervisor Successfully transferred back to supervisor Update from node supervisor: ================================== Ai Message ================================== Name: supervisor The US GDP in 2024 was $29.017 trillion, and New York State's GDP was $2.284 trillion. New York State accounted for approximately 7.87% of the total US GDP in 2024. 3. 從頭開始創建監督者 設置主管如何與個別代理溝通 創建監督代理人 將監督代理和工作代理合併為單一多代理圖。 設置代理通信 我們需要定義一種方法讓監督代理與工作代理進行溝通。在多代理架構中,實現這一點的一種常見方法是使用交接,讓一個代理將控制權交給另一個代理。交接允許您指定: destination: target agent to transfer to目的地:目標代理以轉移至 payload: information to pass to that agentpayload: 傳遞給該代理的信息 我們將通過交接工具實施交接,並將這些工具交給監督代理:當監督代理調用這些工具時,將把控制權交給工作代理,並將完整的消息歷史傳遞給該代理。 from typing import Annotated from langchain_core.tools import tool, InjectedToolCallId from langgraph.prebuilt import InjectedState from langgraph.graph import StateGraph, START, MessagesState from langgraph.types import Command def create_handoff_tool(agent_name: str, description: str = None): """創建任務交接工具""" name = f"transfer_to_{agent_name}" description = description or f"將任務交給 {agent_name}" @tool(name, description=description) def handoff_tool( state: Annotated[MessagesState, InjectedState], tool_call_id: Annotated[str, InjectedToolCallId], ) -> Command: return Command( goto=agent_name, update={ **state, "messages": state["messages"] + [{ "role": "tool", "content": f"已轉交給 {agent_name}", "name": name, "tool_call_id": tool_call_id, }] }, graph=Command.PARENT, ) return handoff_tool # 交接工具 assign_to_research_agent = create_handoff_tool( "research_agent", "分配研究任務" ) assign_to_math_agent = create_handoff_tool( "math_agent", "分配計算任務" ) 創建監督代理人 然後,讓我們使用剛剛定義的交接工具來創建監督代理。我們將使用預建的create_react_agent: supervisor_agent = create_react_agent( model="openai:gpt-4.1", tools=[assign_to_research_agent, assign_to_math_agent], prompt=( "你是團隊主管,負責協調和管理專業代理團隊。\n\n" "【團隊成員】\n" "1. 研究代理:專門處理研究相關任務\n" " - 信息搜索、資料收集\n" " - 市場分析、競爭調研\n" " - 文獻查找、數據驗證\n\n" "2. 數學代理:專門處理計算相關任務\n" " - 數學運算、公式計算\n" " - 統計分析、數值處理\n" " - 財務計算、數據建模\n\n" "【工作原則】\n" "- 根據任務性質分配給合適的代理\n" "- 一次只委派給一個代理,確保專注執行\n" "- 作為主管只負責任務分配和協調\n" "- 不親自執行具體工作任務" ), name="supervisor", ) 創建多代理圖形 把這一切結合在一起,讓我們為整體多代理系統創建一個圖。我們將添加監督者和個別代理作為子圖節點。 from langgraph.graph import END # Define the multi-agent supervisor graph supervisor = ( StateGraph(MessagesState) # NOTE: `destinations` is only needed for visualization and doesn't affect runtime behavior .add_node(supervisor_agent, destinations=("research_agent", "math_agent", END)) .add_node(research_agent) .add_node(math_agent) .add_edge(START, "supervisor") # always return back to the supervisor .add_edge("research_agent", "supervisor") .add_edge("math_agent", "supervisor") .compile() ) 請注意,我們已經添加了從工作代理返回到監督者的明確邊緣——這意味著他們保證將控制權返回給監督者。如果您希望代理直接回應用戶(即將系統變成路由器,您可以移除這些邊緣)。 from IPython.display import display, Image display(Image(supervisor.get_graph().draw_mermaid_png())) 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: $29.017 trillion (nominal, current prices) - New York state GDP in 2024: $2.284 trillion - New York state's share of US GDP in 2024: 7.87% 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 US GDP in 2024: $29.017 trillion New York state GDP in 2024: $2.284 trillion New York state's share of US GDP: 7.87% Update from node supervisor: ================================== Ai Message ================================== Name: supervisor US GDP in 2024 was $29.017 trillion. New York state GDP in 2024 was $2.284 trillion. New York state's GDP was about 7.87% of the 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_qxk9abrxWYQT6a9hPNpXiuM0) Call ID: call_qxk9abrxWYQT6a9hPNpXiuM0 Args: ================================= Tool Message ================================= Name: transfer_to_research_agent Successfully transferred to research_agent ================================== Ai Message ================================== Name: research_agent Tool Calls: tavily_search (call_A3cVm1BXDD8dYv6uLwO132gg) Call ID: call_A3cVm1BXDD8dYv6uLwO132gg Args: query: US GDP 2024 search_depth: advanced tavily_search (call_77JyoUYwGDXlRNKOwvQFUUYJ) Call ID: call_77JyoUYwGDXlRNKOwvQFUUYJ Args: query: New York state GDP 2024 search_depth: advanced ================================= Tool Message ================================= Name: tavily_search {"query": "US GDP 2024", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://tradingeconomics.com/united-states/gdp-growth", "title": "United States GDP Growth Rate - Trading Economics", "content": "The US economy expanded an annualized 2.4% in Q4 2024, slightly higher than 2.3% in the previous estimates, primarily reflecting a downward revision to imports. Exports fell slightly less (-0.2% vs -0.5%) and imports declined more than initially anticipated (-1.9% vs -1.2%), leaving the contribution from net trade positive at 0.26 pp (vs 0.12 pp). Government expenditure also rose more (3.1% vs 2.9%) and fixed investment contracted less (-1.1% vs -1.4%), due to equipment (-8.7% vs -9%) while [...] The Gross Domestic Product (GDP) in the United States expanded 2.40 percent in the fourth quarter of 2024 over the previous quarter. GDP Growth Rate in the United States averaged 3.21 percent from 1947 until 2024, reaching an all time high of 35.20 percent in the third quarter of 2020 and a record low of -28.10 percent in the second quarter of 2020. This page provides the latest reported value for - United States GDP Growth Rate - plus previous releases, historical high and low, short-term [...] The Gross Domestic Product (GDP) in the United States expanded 2.40 percent in the fourth quarter of 2024 over the previous quarter. GDP Growth Rate in the United States is expected to be 0.90 percent by the end of this quarter, according to Trading Economics global macro models and analysts expectations. In the long-term, the United States GDP Growth Rate is projected to trend around 2.00 percent in 2026, according to our econometric models.\n%\n3Y5Y10YMAX\nExport API\nOK\nLoading...", "score": 0.9071234, "raw_content": null}, {"url": "https://www.bea.gov/data/gdp/gross-domestic-product", "title": "Gross Domestic Product | U.S. Bureau of Economic Analysis (BEA)", "content": "Real gross domestic product (GDP) increased at an annual rate of 2.4 percent in the fourth quarter of 2024 (October, November, and December), according to the third estimate released by the U.S. Bureau of Economic Analysis. In the third quarter, real GDP increased 3.1 percent. The increase in real GDP in the fourth quarter primarily reflected increases in consumer spending and government spending that were partly offset by a decrease in investment. Imports, which are a subtraction in the", "score": 0.9008183, "raw_content": null}, {"url": "https://www.nerdwallet.com/article/finance/gdp-report", "title": "GDP Report: Final Estimate Shows Growth Increased 2.4% in Q4 2024", "content": "NerdWallet's content is fact-checked for accuracy, timeliness and relevance. It undergoes a thorough review process involving writers and editors to ensure the information is as clear and complete as possible.\n\nAnna Helhoski\n\nRick VanderKnyff\n\nUpdated on April 7\n\nReal gross domestic product increased by an annual rate of 2.4% in the fourth quarter of 2024, according to the third estimate report released on March 27 by the Bureau of Economic Analysis. [...] The third estimate also showed that in 2024, the U.S. GDP grew 2.8% compared to a 2.9% increase in 2023.\n\nQ1 2025 GDP forecasts are negative\n\nA forecasting tool published by the Atlanta Federal Reserve shows negative growth for the first quarter of 2025; it expects gross domestic product (GDP) to contract by rate of -2.8%, according to data released on March 28. If the forecast is correct, it would be the first quarter where GDP declined since the first and second quarters of 2022. [...] GDP could be the next concern: On March 3, a forecasting tool published by the Atlanta Federal Reserve showed that GDP could contract by a rate of -2.8% in the first quarter of 2025. If GDP does indeed decline, it would be the first time since the first and second quarters of 2022.\n\nIn 2024, the U.S. GDP grew 2.8% compared to a 2.9% increase in 2023, according to a second estimate of real gross domestic product from the Bureau of Economic Analysis, released Feb. 27.", "score": 0.89053273, "raw_content": null}], "response_time": 1.78} ================================= Tool Message ================================= Name: tavily_search {"query": "New York state GDP 2024", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://en.wikipedia.org/wiki/Economy_of_New_York_(state)", "title": "Economy of New York (state) - Wikipedia", "content": "Jump to content\nMain menu\nSearch\nDonate\nCreate account\nLog in\nPersonal tools\nToggle the table of contents\nEconomy of New York (state)\n1 language\nArticle\nTalk\nRead\nEdit\nView history\nTools\nFrom Wikipedia, the free encyclopedia\nThis article is about the overall economy of New York State. For the economy of New York City, see Economy of New York City.\nEconomy of New York\nNew York City, the economic capital of New York (state)\nStatistics\nGDP $2.3 trillion (2024)[1]\nGDP per capita $117,332 (2024)[2] [...] The economy of the State of New York is reflected in its gross state product in 2024 of $2.284 trillion, ranking third in size behind the larger states of California and Texas. If New York State were an independent nation, it would rank as the 10th largest economy in the world by nominal GDP. However, in 2019, the multi-state, New York City-centered metropolitan statistical area produced a gross metropolitan product (GMP) of $US2.0 trillion, ranking first nationally by a wide margin and would [...] Population below poverty line 13.6%[3]\nGini coefficient 0.5157 ± 0.0029 (2023)[4]\nLabour force 9,645,984 (2023)[5]\nUnemployment 4.4% (August 2024)[6]\nPublic finances\nRevenues $63.5 billion[7]\nExpenses $54.6 billion[8]", "score": 0.9511106, "raw_content": null}, {"url": "https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_GDP", "title": "List of U.S. states and territories by GDP - Wikipedia", "content": "GDP per capita also varied widely throughout the United States in 2024, with New York ($117,332), Massachusetts ($110,561), and Washington (state) ($108,468) recording the three highest GDP per capita figures in the U.S., while Mississippi ($53,061), Arkansas ($60,276), and West Virginia ($60,783) recorded the three lowest GDP per capita figures in the U.S. The District of Columbia, though, recorded a GDP per capita figure far higher than any U.S. state in 2024 at $263,220. [...] Overall, in the calendar year 2024, the United States' Nominal GDP at Current Prices totaled at $29.017 trillion, as compared to $25.744 trillion in 2022.\nThe three U.S. states with the highest GDPs were California ($4.080 trillion), Texas ($2.695 trillion), and New York ($2.284 trillion). The three U.S. states with the lowest GDPs were Vermont ($45.4 billion), Wyoming ($53.0 billion), and Alaska ($69.8 billion).", "score": 0.8947989, "raw_content": null}, {"url": "https://edc.nyc/sites/default/files/2025-01/NYCEDC-State-of-the-NYC-Economy-2024-v3.pdf", "title": "[PDF] State of the New York City Economy - NYCEDC", "content": "for talent faced a limited supply. STATE OF THE NEW YORK CITY ECONOMY 2024 / 21 STATE OF THE NEW YORK CITY ECONOMY 2024 / 22 After losing nearly a million jobs during the COVID-19 pandemic, New York City is now at record-high levels of private and total employment. The city’s gross city product (GCP) stands at $1.18 trillion as of 2023.24 While legacy sectors such as Finance and Insurance have continued to play a vital part in the city’s economic successes, emerging sectors like Tech, the Green [...] STATE OF THE NEW YORK CITY ECONOMY 2024 / 11 New York City’s economy is the largest in the nation, with $2 trillion in gross metropolitan product (GMP) for the metro area, representing 9% of the total US economy. As such, the city’s economy is closely intertwined with the broader national economic landscape, and US macroeconomic conditions play a significant role in shaping the economic backdrop for the city. National interest rates, inflation, gross domestic product (GDP), and employment [...] 1 Macro Trends STATE OF THE NEW YORK CITY ECONOMY 2024 / 12 Output Has Grown Faster in NYC than Nationally Since 2022 Actual and Projected US Real GDP and NYC Real GCP Growth Rates 2019 2020 2021 2022 2023 2024* 2025* NYC 2.6% -4.2% 5.5% 2.6% 2.8% 3.6% 1.9% US 2.5% -2.2% 5.8% 1.9% 2.5% 2.5% 1.4% Source: NYC OMB and US Bureau of Economic Analysis. Projections for 2024 and and 2025 from NYC OMB.", "score": 0.85797083, "raw_content": null}], "response_time": 0.63} ================================== Ai Message ================================== Name: research_agent - US GDP in 2024: $29.017 trillion (nominal, current prices) - New York state GDP in 2024: $2.284 trillion - New York state's share of US GDP in 2024: 7.87% ================================== Ai Message ================================== Name: supervisor Tool Calls: transfer_to_math_agent (call_m5ICqaoAtRXHWb8BI3638dJL) Call ID: call_m5ICqaoAtRXHWb8BI3638dJL Args: ================================= Tool Message ================================= Name: transfer_to_math_agent Successfully transferred to math_agent ================================== Ai Message ================================== Name: math_agent Tool Calls: divide (call_Sf7nvyvEgIaoDlaioPmkCdqz) Call ID: call_Sf7nvyvEgIaoDlaioPmkCdqz Args: a: 2.284 b: 29.017 ================================= Tool Message ================================= Name: divide 0.07871247889168417 ================================== Ai Message ================================== Name: math_agent US GDP in 2024: $29.017 trillion New York state GDP in 2024: $2.284 trillion New York state's share of US GDP: 7.87% ================================== Ai Message ================================== Name: supervisor US GDP in 2024 was $29.017 trillion. New York state GDP in 2024 was $2.284 trillion. New York state's GDP was about 7.87% of the US GDP. 您可以看到監督系統將所有個別代理的訊息(即它們的內部工具調用循環)附加到完整的訊息歷史中。這意味著在每次監督者回合中,監督代理都會看到這個完整的歷史。如果您想要更多控制: how inputs are passed to agents: you can use LangGraph Send() primitive to directly send data to the worker agents during the handoff. See the task delegation example below如何將輸入傳遞給代理:您可以使用 LangGraph Send() 原語在交接期間直接將數據發送給工作代理。請參閱下面的任務委派示例。 how agent outputs are added: you can control how much of the agent's internal message history is added to the overall supervisor message history by wrapping the agent in a separate node function:如何添加代理輸出:您可以通過將代理包裝在一個單獨的節點函數中來控制代理的內部消息歷史添加到整體監督者消息歷史中的程度: def call_research_agent(state): # return agent's final response, # excluding inner monologue response = research_agent.invoke(state) return {"messages": response["messages"][-1]} 4. 建立委派任務 到目前為止,個別代理依賴於解釋完整的消息歷史來確定他們的任務。另一種方法是要求主管明確制定任務。我們可以通過向handoff_tool函數添加task_description參數來實現。 from langgraph.types import Send def create_task_description_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( # this is populated by the supervisor LLM task_description: Annotated[ str, "Description of what the next agent should do, including all of the relevant context.", ], # these parameters are ignored by the LLM state: Annotated[MessagesState, InjectedState], ) -> Command: task_description_message = {"role": "user", "content": task_description} agent_input = {**state, "messages": [task_description_message]} return Command( goto=[Send(agent_name, agent_input)], graph=Command.PARENT, ) return handoff_tool assign_to_research_agent_with_description = create_task_description_handoff_tool( agent_name="research_agent", description="Assign task to a researcher agent.", ) assign_to_math_agent_with_description = create_task_description_handoff_tool( agent_name="math_agent", description="Assign task to a math agent.", ) supervisor_agent_with_description = create_react_agent( model="openai:gpt-4.1", tools=[ assign_to_research_agent_with_description, assign_to_math_agent_with_description, ], prompt=( "You are a supervisor managing two agents:\n" "- a research agent. Assign research-related tasks to this assistant\n" "- a math agent. Assign math-related tasks to this assistant\n" "Assign work to one agent at a time, do not call agents in parallel.\n" "Do not do any work yourself." ), name="supervisor", ) supervisor_with_description = ( StateGraph(MessagesState) .add_node( supervisor_agent_with_description, destinations=("research_agent", "math_agent") ) .add_node(research_agent) .add_node(math_agent) .add_edge(START, "supervisor") .add_edge("research_agent", "supervisor") .add_edge("math_agent", "supervisor") .compile() ) 我們在handoff_tool中使用Send()原語。這意味著每個工作代理僅看到Send有效負載的內容,而不是接收完整的supervisor圖狀態作為輸入。在此示例中,我們將任務描述作為單一的「人類」消息發送。 現在讓我們用相同的輸入查詢來運行它: 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?", } ] }, subgraphs=True, ): pretty_print_messages(chunk, last_message=True) Update from subgraph supervisor: Update from node agent: ================================== Ai Message ================================== Name: supervisor Tool Calls: transfer_to_research_agent (call_TtKzjGQBe4X9Xh0VzmjStVgZ) Call ID: call_TtKzjGQBe4X9Xh0VzmjStVgZ Args: Update from subgraph research_agent: Update from node agent: ================================== Ai Message ================================== Name: research_agent Tool Calls: tavily_search (call_AfeRYBJxJtmD4EKqifYcx8EI) Call ID: call_AfeRYBJxJtmD4EKqifYcx8EI Args: query: US GDP in 2024 search_depth: advanced tavily_search (call_n7Dn8QnDLu2ZpEDzswS2MOJ8) Call ID: call_n7Dn8QnDLu2ZpEDzswS2MOJ8 Args: query: New York state GDP in 2024 search_depth: advanced Update from subgraph research_agent: Update from node tools: ================================= Tool Message ================================= Name: tavily_search {"query": "New York state GDP in 2024", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://en.wikipedia.org/wiki/Economy_of_New_York_(state)", "title": "Economy of New York (state) - Wikipedia", "content": "Jump to content\nMain menu\nSearch\nDonate\nCreate account\nLog in\nPersonal tools\nToggle the table of contents\nEconomy of New York (state)\n1 language\nArticle\nTalk\nRead\nEdit\nView history\nTools\nFrom Wikipedia, the free encyclopedia\nThis article is about the overall economy of New York State. For the economy of New York City, see Economy of New York City.\nEconomy of New York\nNew York City, the economic capital of New York (state)\nStatistics\nGDP $2.3 trillion (2024)[1]\nGDP per capita $117,332 (2024)[2] [...] The economy of the State of New York is reflected in its gross state product in 2024 of $2.284 trillion, ranking third in size behind the larger states of California and Texas. If New York State were an independent nation, it would rank as the 10th largest economy in the world by nominal GDP. However, in 2019, the multi-state, New York City-centered metropolitan statistical area produced a gross metropolitan product (GMP) of $US2.0 trillion, ranking first nationally by a wide margin and would [...] Population below poverty line 13.6%[3]\nGini coefficient 0.5157 ± 0.0029 (2023)[4]\nLabour force 9,645,984 (2023)[5]\nUnemployment 4.4% (August 2024)[6]\nPublic finances\nRevenues $63.5 billion[7]\nExpenses $54.6 billion[8]", "score": 0.9530353, "raw_content": null}, {"url": "https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_GDP", "title": "List of U.S. states and territories by GDP - Wikipedia", "content": "GDP per capita also varied widely throughout the United States in 2024, with New York ($117,332), Massachusetts ($110,561), and Washington (state) ($108,468) recording the three highest GDP per capita figures in the U.S., while Mississippi ($53,061), Arkansas ($60,276), and West Virginia ($60,783) recorded the three lowest GDP per capita figures in the U.S. The District of Columbia, though, recorded a GDP per capita figure far higher than any U.S. state in 2024 at $263,220. [...] Overall, in the calendar year 2024, the United States' Nominal GDP at Current Prices totaled at $29.017 trillion, as compared to $25.744 trillion in 2022.\nThe three U.S. states with the highest GDPs were California ($4.080 trillion), Texas ($2.695 trillion), and New York ($2.284 trillion). The three U.S. states with the lowest GDPs were Vermont ($45.4 billion), Wyoming ($53.0 billion), and Alaska ($69.8 billion).", "score": 0.89997756, "raw_content": null}, {"url": "https://edc.nyc/sites/default/files/2025-01/NYCEDC-State-of-the-NYC-Economy-2024-v3.pdf", "title": "[PDF] State of the New York City Economy - NYCEDC", "content": "for talent faced a limited supply. STATE OF THE NEW YORK CITY ECONOMY 2024 / 21 STATE OF THE NEW YORK CITY ECONOMY 2024 / 22 After losing nearly a million jobs during the COVID-19 pandemic, New York City is now at record-high levels of private and total employment. The city’s gross city product (GCP) stands at $1.18 trillion as of 2023.24 While legacy sectors such as Finance and Insurance have continued to play a vital part in the city’s economic successes, emerging sectors like Tech, the Green [...] STATE OF THE NEW YORK CITY ECONOMY 2024 / 11 New York City’s economy is the largest in the nation, with $2 trillion in gross metropolitan product (GMP) for the metro area, representing 9% of the total US economy. As such, the city’s economy is closely intertwined with the broader national economic landscape, and US macroeconomic conditions play a significant role in shaping the economic backdrop for the city. National interest rates, inflation, gross domestic product (GDP), and employment [...] 1 Macro Trends STATE OF THE NEW YORK CITY ECONOMY 2024 / 12 Output Has Grown Faster in NYC than Nationally Since 2022 Actual and Projected US Real GDP and NYC Real GCP Growth Rates 2019 2020 2021 2022 2023 2024* 2025* NYC 2.6% -4.2% 5.5% 2.6% 2.8% 3.6% 1.9% US 2.5% -2.2% 5.8% 1.9% 2.5% 2.5% 1.4% Source: NYC OMB and US Bureau of Economic Analysis. Projections for 2024 and and 2025 from NYC OMB.", "score": 0.8616433, "raw_content": null}], "response_time": 2.35} Update from subgraph research_agent: Update from node agent: ================================== Ai Message ================================== Name: research_agent - US GDP in 2024 was $29.017 trillion (nominal, current prices) ([source](https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_GDP)). - New York State GDP in 2024 was $2.284 trillion ([source](https://en.wikipedia.org/wiki/Economy_of_New_York_(state))). Percentage of US GDP attributed to New York State in 2024: approximately 7.9%. Update from subgraph supervisor: Update from node agent: ================================== Ai Message ================================== Name: supervisor Tool Calls: transfer_to_math_agent (call_oYbIXhQQeTWlj2zvZSoStUgO) Call ID: call_oYbIXhQQeTWlj2zvZSoStUgO Args: Update from subgraph math_agent: Update from node agent: ================================== Ai Message ================================== Name: math_agent Tool Calls: divide (call_K5QxmkQYFfCZw5Vzkbz43VIG) Call ID: call_K5QxmkQYFfCZw5Vzkbz43VIG Args: a: 2.284 b: 29.017 Update from subgraph math_agent: Update from node tools: ================================= Tool Message ================================= Name: divide 0.07871247889168417 Update from subgraph math_agent: Update from node agent: ================================== Ai Message ================================== Name: math_agent New York state's GDP was approximately 7.87% of US GDP in 2024. Update from subgraph supervisor: Update from node agent: ================================== Ai Message ================================== Name: supervisor Here are the findings: - US GDP in 2024: $29.017 trillion - New York State GDP in 2024: $2.284 trillion - New York State accounted for approximately 7.87% of US GDP in 2024. 試試看台灣的經濟股市相關問題!! import os import getpass from langchain_tavily import TavilySearch from langgraph.prebuilt import create_react_agent from langchain.chat_models import init_chat_model from typing import Annotated from langchain_core.tools import tool, InjectedToolCallId from langgraph.prebuilt import InjectedState from langgraph.graph import StateGraph, START, END, MessagesState from langgraph.types import Command from langchain_core.messages import HumanMessage # 設置 API 金鑰 if not os.environ.get("OPENAI_API_KEY"): os.environ["OPENAI_API_KEY"] = getpass.getpass("請輸入 OpenAI API Key: ") if not os.environ.get("TAVILY_API_KEY"): os.environ["TAVILY_API_KEY"] = getpass.getpass("請輸入 Tavily API Key: ") # 創建研究工具 web_search = TavilySearch(max_results=3) # 創建數學工具 - 使用英文函數名但中文說明 @tool def add(a: float, b: float) -> float: """Add two numbers (將兩個數字相加)""" return a + b @tool def multiply(a: float, b: float) -> float: """Multiply two numbers (將兩個數字相乘)""" return a * b @tool def divide(a: float, b: float) -> float: """Divide two numbers (將兩個數字相除)""" if b == 0: return "錯誤:除數不能為零" return a / b @tool def calculate_growth_rate(initial: float, final: float) -> float: """Calculate growth rate (計算成長率)""" if initial == 0: return "錯誤:初始值不能為零" return ((final - initial) / initial) * 100 @tool def calculate_percentage(part: float, whole: float) -> float: """Calculate percentage (計算百分比)""" if whole == 0: return "錯誤:總數不能為零" return (part / whole) * 100 # 創建研究代理 research_agent = create_react_agent( model="gpt-4", tools=[web_search], prompt=( "你是一個經濟研究助理。\n\n" "任務說明:\n" "- 只協助處理經濟數據查詢、市場調查等研究任務\n" "- 不要進行任何數學計算,計算任務請交給數學代理\n" "- 完成任務後,直接向主管回報研究結果\n" "- 只回報研究發現,不要加入其他無關文字" ), name="research_agent", ) # 創建數學代理 math_agent = create_react_agent( model="gpt-4", tools=[add, multiply, divide, calculate_growth_rate, calculate_percentage], prompt=( "你是一個數學計算專家。\n\n" "任務說明:\n" "- 只處理數學計算、統計分析等任務\n" "- 專注於財經數據的計算(如成長率、百分比、比例等)\n" "- 完成計算後,直接向主管回報結果\n" "- 只回報計算結果,不要加入其他解釋" ), name="math_agent", ) # 創建任務交接工具 - 保持英文名稱 def create_handoff_tool(*, agent_name: str, description: str | None = None): name = f"transfer_to_{agent_name}" description = description or f"Transfer task to {agent_name}" @tool(name, description=description) def handoff_tool( state: Annotated[MessagesState, InjectedState], tool_call_id: Annotated[str, InjectedToolCallId], ) -> Command: tool_message = { "role": "tool", "content": f"任務已成功轉交給 {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 economic research tasks to research assistant (將經濟研究任務分配給研究助理)", ) assign_to_math_agent = create_handoff_tool( agent_name="math_agent", description="Assign calculation tasks to math expert (將數學計算任務分配給計算專家)", ) # 創建監督代理(主管) supervisor_agent = create_react_agent( model="gpt-4", tools=[assign_to_research_agent, assign_to_math_agent], prompt=( "你是一位專案經理,管理兩個專業團隊:\n" "- 研究助理:負責查詢經濟數據、市場資訊等研究任務\n" "- 計算專家:負責數學計算、財務分析等計算任務\n\n" "工作規則:\n" "- 一次只分配任務給一個團隊,不要同時派工\n" "- 你只負責分配任務,不要親自執行工作\n" "- 根據任務性質選擇適合的團隊" ), name="supervisor", ) # 創建多代理系統圖 supervisor = ( StateGraph(MessagesState) .add_node(supervisor_agent) .add_node(research_agent) .add_node(math_agent) .add_edge(START, "supervisor") .add_edge("research_agent", "supervisor") .add_edge("math_agent", "supervisor") .compile() ) # 執行台灣相關的經濟問題查詢 print("=== 開始執行多代理系統 ===") # 測試簡單問題 simple_query = "台灣2023年GDP是多少?如果成長3%,2024年會是多少?" print(f"\n測試問題: {simple_query}") print("-" * 50) try: # 使用 invoke 而不是 stream 來避免錯誤 result = supervisor.invoke( {"messages": [HumanMessage(content=simple_query)]} ) # 顯示結果 print("\n執行結果:") for i, msg in enumerate(result["messages"]): msg_type = type(msg).__name__ content = getattr(msg, 'content', str(msg)) if content and not content.startswith("任務已成功轉交"): print(f"{i+1}. {msg_type}: {content[:200]}...") except Exception as e: print(f"執行錯誤: {type(e).__name__}: {e}") # 更多台灣經濟問題範例 taiwan_economic_queries = [ "查詢台積電最新股價,如果我有100萬元,可以買幾張?", "台北市平均房價每坪80萬,新北市每坪50萬,價差是多少百分比?", "如果美元兌台幣是31.5,歐元兌台幣是34.2,1萬歐元可以換多少美元?", "台灣基本工資月薪27,470元,如果明年調漲5%,會是多少?", ] # 執行一個範例 print(f"\n\n執行範例查詢: {taiwan_economic_queries[0]}") print("-" * 50) try: result2 = supervisor.invoke( {"messages": [HumanMessage(content=taiwan_economic_queries[0])]} ) # 只顯示重要訊息 for msg in result2["messages"]: if hasattr(msg, 'content') and msg.content: content = msg.content if any(keyword in content for keyword in ["研究結果", "計算結果", "股價", "張"]): print(f"→ {content}") except Exception as e: print(f"執行錯誤: {type(e).__name__}: {e}") # 簡化的直接測試 print("\n\n=== 簡化測試 ===") try: # 直接測試數學代理 math_result = math_agent.invoke({ "messages": [HumanMessage(content="計算 100萬除以600 (假設台積電股價600元)")] }) print("數學代理測試成功") # 直接測試研究代理 research_result = research_agent.invoke({ "messages": [HumanMessage(content="查詢台積電最新股價")] }) print("研究代理測試成功") except Exception as e: print(f"測試錯誤: {type(e).__name__}: {e}")