langgraph 多智能体 Multi-agent supervisor

1. 工具定义

1.1网络搜索工具

from typing import Annotated
import os
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool
from langchain_experimental.utilities import PythonREPLos.environ["TAVILY_API_KEY"] = "your api key"
tavily_tool = TavilySearchResults(max_results=3)

1.2 代码执行工具

from autogen_core.base import CancellationToken
from autogen_core.components.tools import PythonCodeExecutionTool
from autogen_ext.code_executors import DockerCommandLineCodeExecutor# Create the tool.
code_executor = DockerCommandLineCodeExecutor()
await code_executor.start()
code_execution_tool = PythonCodeExecutionTool(code_executor)
cancellation_token = CancellationToken()from langgraph.prebuilt import ToolNode@tool
async def code_executor(code: Annotated[str, "The python code to execute."],                        
):"""Use this to execute python code. If you want to see the output of a value,you should print it out with `print(...)`. This is visible to the user."""try:result = await code_execution_tool.run_json({"code": code}, cancellation_token)except BaseException as e:return f"Failed to execute. Error: {repr(e)}"result= code_execution_tool.return_value_as_string(result)result_str = f"The result is:{result}"return result_str

2. graph中各节点定义

from langgraph.graph import MessagesState# The agent state is the input to each node in the graph
class AgentState(MessagesState):# The 'next' field indicates where to route to nextnext: str
from typing import Literal
from typing_extensions import TypedDictfrom langchain_openai import ChatOpenAI### Edges
llm = ChatOpenAI(temperature=0,model="GLM-4-plus",openai_api_key="your api key",openai_api_base="https://open.bigmodel.cn/api/paas/v4/"
)members = ["researcher", "coder"]
# Our team supervisor is an LLM node. It just picks the next agent to process
# and decides when the work is completed
options = members + ["FINISH"]system_prompt = ("You are a supervisor tasked with managing a conversation between the"f" following workers: {members}. Given the following user request,"" respond with the worker to act next. Each worker will perform a"" task and respond with their results and status. When finished,"" respond with FINISH."
)
from langchain_core.messages import HumanMessage
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import create_react_agentclass Router(TypedDict):"""Worker to route to next. If no workers needed, response 'FINISH'."""next: Literal[*options]async def supervisor_node(state: AgentState) -> AgentState:messages = [{"role": "system", "content": system_prompt},] + state["messages"]response = await llm.with_structured_output(Router).ainvoke(messages)next_ = response["next"]if "FINISH" in next_:next_ = ENDreturn {"next": next_}research_agent = create_react_agent(llm, tools=[tavily_tool], state_modifier="You only provide information. Don't do the math."
)async def research_node(state: AgentState) -> AgentState:result = await research_agent.ainvoke(state)return {"messages": [HumanMessage(content=result["messages"][-1].content, name="researcher")]}# NOTE: THIS PERFORMS ARBITRARY CODE EXECUTION, WHICH CAN BE UNSAFE WHEN NOT SANDBOXED
code_agent = create_react_agent(llm, tools=[code_executor],state_modifier="""when you use the code tool,it only detect the code block in markdown format."""             )async def code_node(state: AgentState) -> AgentState:result = await code_agent.ainvoke(state)return {"messages": [HumanMessage(content=result["messages"][-1].content, name="coder")]}builder = StateGraph(AgentState)
builder.add_edge(START, "supervisor")
builder.add_node("supervisor", supervisor_node)
builder.add_node("researcher", research_node)
builder.add_node("coder", code_node)
<langgraph.graph.state.StateGraph at 0x23c52d56c60>

3. graph中的边定义

for member in members:# We want our workers to ALWAYS "report back" to the supervisor when donebuilder.add_edge(member, "supervisor")# The supervisor populates the "next" field in the graph state
# which routes to a node or finishes
builder.add_conditional_edges("supervisor", lambda state: state["next"])
# Finally, add entrypoint
builder.add_edge(START, "supervisor")graph = builder.compile()
from IPython.display import display, Image
display(Image(graph.get_graph().draw_mermaid_png()))

请添加图片描述

4. 示例

4.1 第一个例子

问题: What's the square root of 42?

async for s in graph.astream({"messages": [("user", "What's the square root of 42?")]}, subgraphs=True
):print(s)print("----")
((), {'supervisor': {'next': 'coder'}})
----
(('coder:7c74ccb6-c024-13da-c40d-83d4f5bb3251',), {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_-9181532423403291248', 'function': {'arguments': '{"code": "import math\\nprint(math.sqrt(42))"}', 'name': 'code_executor'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 18, 'prompt_tokens': 190, 'total_tokens': 208, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-d809acc4-d589-4227-ae66-96a4908305bc-0', tool_calls=[{'name': 'code_executor', 'args': {'code': 'import math\nprint(math.sqrt(42))'}, 'id': 'call_-9181532423403291248', 'type': 'tool_call'}], usage_metadata={'input_tokens': 190, 'output_tokens': 18, 'total_tokens': 208, 'input_token_details': {}, 'output_token_details': {}})]}})
----
(('coder:7c74ccb6-c024-13da-c40d-83d4f5bb3251',), {'tools': {'messages': [ToolMessage(content='The result is:6.48074069840786\n', name='code_executor', id='9127536d-111b-4de9-9ecf-769a369e619d', tool_call_id='call_-9181532423403291248')]}})
----
(('coder:7c74ccb6-c024-13da-c40d-83d4f5bb3251',), {'agent': {'messages': [AIMessage(content='The square root of 42 is approximately 6.4807.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 16, 'prompt_tokens': 225, 'total_tokens': 241, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-b7554cd1-c355-4ad4-8482-5a27ad2afa9a-0', usage_metadata={'input_tokens': 225, 'output_tokens': 16, 'total_tokens': 241, 'input_token_details': {}, 'output_token_details': {}})]}})
----
((), {'coder': {'messages': [HumanMessage(content='The square root of 42 is approximately 6.4807.', additional_kwargs={}, response_metadata={}, name='coder')]}})
----
((), {'supervisor': {'next': '__end__'}})
----

4.2 第二个例子

问题:Find the latest GDP of New York and California, then calculate the average

async for s in graph.astream({"messages": [("user","Find the latest GDP of New York and California, then calculate the average",)]},subgraphs=True,
):print(s)print("----")
((), {'supervisor': {'next': 'researcher'}})
----
(('researcher:1c6c3cb9-b2d8-3632-e480-a307b53f1d77',), {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_-9181536546572673495', 'function': {'arguments': '{"query": "latest GDP of New York 2023"}', 'name': 'tavily_search_results_json'}, 'type': 'function', 'index': 0}, {'id': 'call_-9181536546572673494', 'function': {'arguments': '{"query": "latest GDP of California 2023"}', 'name': 'tavily_search_results_json'}, 'type': 'function', 'index': 1}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 41, 'prompt_tokens': 170, 'total_tokens': 211, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-7553ea17-b477-45ff-973b-15c3584bfca9-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'latest GDP of New York 2023'}, 'id': 'call_-9181536546572673495', 'type': 'tool_call'}, {'name': 'tavily_search_results_json', 'args': {'query': 'latest GDP of California 2023'}, 'id': 'call_-9181536546572673494', 'type': 'tool_call'}], usage_metadata={'input_tokens': 170, 'output_tokens': 41, 'total_tokens': 211, 'input_token_details': {}, 'output_token_details': {}})]}})
----
(('researcher:1c6c3cb9-b2d8-3632-e480-a307b53f1d77',), {'tools': {'messages': [ToolMessage(content='[{"url": "https://countryeconomy.com/gdp/usa-states/new-york", "content": "New York - GDP at market prices 2023 | countryeconomy.com US States GDP at market prices New York - GDP at market prices | 2023 | €2,008,702M | $2,172,010M | 1.5% | | 2022 | €1,949,439M | $2,052,759M | 1.7% | | 2021 | €1,626,290M | $1,923,413M | 4.8% | | 2020 | €1,552,591M | $1,773,370M | -2.8% | | 2019 | €1,596,669M | $1,787,471M | 2.4% | Evolution: GDP growth rate at constant prices New York Argentina: Fitch:Long Term Foreign currency Sovereign rating Barbados: Fitch:Long Term Foreign currency Sovereign rating Croatia: Fitch:Long Term Foreign currency Sovereign rating Egypt: Fitch:Long Term Foreign currency Sovereign rating Mongolia: Fitch:Long Term Foreign currency Sovereign rating Tunisia: Fitch:Long Term Foreign currency Sovereign rating"}, {"url": "https://www.bls.gov/regions/northeast/summary/blssummary_newyorkcity.pdf", "content": "New York City Economic Summary. Updated November 01, 2024. ... May 2023 New York area United States $39.45 $31.48 Prices paid by urban consumers for selected categories, over-the-year change Selling prices received by producers for selected industries nationwide, over-the-year change"}, {"url": "https://fred.stlouisfed.org/series/NYNGSP", "content": "Gross Domestic Product: All Industry Total in New York (NYNGSP) | FRED | St. Louis Fed FRED   About FRED About FRED What is FRED Gross Domestic Product: All Industry Total in New York (NYNGSP) Add data series to graph: U.S. Bureau of Economic Analysis, Gross Domestic Product: All Industry Total in New York [NYNGSP], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/NYNGSP, November 18, 2024. Real Gross Domestic Product: All Industry Total in New York Gross Domestic Product: All Industry Total in New Jersey Gross Domestic Product: All Industry Total in New York Gross State Product New York State Bureau of Economic Analysis Industry Gross Domestic Product Annual Public Domain: Citation Requested Not Seasonally Adjusted United States of America"}]', name='tavily_search_results_json', id='9ed353fe-b950-4b5f-9df1-4bc94514c3c4', tool_call_id='call_-9181536546572673495', artifact={'query': 'latest GDP of New York 2023', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'New York - GDP at market prices 2023 | countryeconomy.com', 'url': 'https://countryeconomy.com/gdp/usa-states/new-york', 'content': 'New York - GDP at market prices 2023 | countryeconomy.com US States GDP at market prices New York - GDP at market prices | 2023 | €2,008,702M | $2,172,010M | 1.5% | | 2022 | €1,949,439M | $2,052,759M | 1.7% | | 2021 | €1,626,290M | $1,923,413M | 4.8% | | 2020 | €1,552,591M | $1,773,370M | -2.8% | | 2019 | €1,596,669M | $1,787,471M | 2.4% | Evolution: GDP growth rate at constant prices New York Argentina: Fitch:Long Term Foreign currency Sovereign rating Barbados: Fitch:Long Term Foreign currency Sovereign rating Croatia: Fitch:Long Term Foreign currency Sovereign rating Egypt: Fitch:Long Term Foreign currency Sovereign rating Mongolia: Fitch:Long Term Foreign currency Sovereign rating Tunisia: Fitch:Long Term Foreign currency Sovereign rating', 'score': 0.99852777, 'raw_content': None}, {'title': 'PDF', 'url': 'https://www.bls.gov/regions/northeast/summary/blssummary_newyorkcity.pdf', 'content': 'New York City Economic Summary. Updated November 01, 2024. ... May 2023 New York area United States $39.45 $31.48 Prices paid by urban consumers for selected categories, over-the-year change Selling prices received by producers for selected industries nationwide, over-the-year change', 'score': 0.98862445, 'raw_content': None}, {'title': 'Gross Domestic Product: All Industry Total in New York', 'url': 'https://fred.stlouisfed.org/series/NYNGSP', 'content': 'Gross Domestic Product: All Industry Total in New York (NYNGSP) | FRED | St. Louis Fed FRED   About FRED About FRED What is FRED Gross Domestic Product: All Industry Total in New York (NYNGSP) Add data series to graph: U.S. Bureau of Economic Analysis, Gross Domestic Product: All Industry Total in New York [NYNGSP], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/NYNGSP, November 18, 2024. Real Gross Domestic Product: All Industry Total in New York Gross Domestic Product: All Industry Total in New Jersey Gross Domestic Product: All Industry Total in New York Gross State Product New York State Bureau of Economic Analysis Industry Gross Domestic Product Annual Public Domain: Citation Requested Not Seasonally Adjusted United States of America', 'score': 0.85452086, 'raw_content': None}], 'response_time': 1.76}), ToolMessage(content='[{"url": "https://www.gov.ca.gov/2024/04/16/california-remains-the-worlds-5th-largest-economy/", "content": "California remains the 5th largest economy in the world since 2017. California is the 5th largest economy in the world for the seventh consecutive year, with a nominal GDP of nearly $3.9 trillion in 2023 and a growth rate of 6.1% since the year prior, according to the U.S. Bureau of Economic Analysis (BEA). On a per capita basis, California is"}, {"url": "https://www.statista.com/statistics/187834/gdp-of-the-us-federal-state-of-california-since-1997/", "content": "Industry Overview\\nDigital & Trend reports\\nOverview and forecasts on trending topics\\nIndustry & Market reports\\nIndustry and market insights and forecasts\\nCompanies & Products reports\\nKey figures and rankings about companies and products\\nConsumer & Brand reports\\nConsumer and brand insights and preferences in various industries\\nPolitics & Society reports\\nDetailed information about political and social topics\\nCountry & Region reports\\nAll key figures about countries and regions\\nMarket forecast and expert KPIs for 1000+ markets in 190+ countries & territories\\nInsights on consumer attitudes and behavior worldwide\\nBusiness information on 100m+ public and private companies\\nExplore Company Insights\\nDetailed information for 39,000+ online stores and marketplaces\\nDirectly accessible data for 170 industries from 150+ countries\\nand over 1\xa0Mio. facts.\\n Statistics on\\n\\"\\nCalifornia\\n\\"\\nOther statistics that may interest you California\\nPopulation\\nEconomy\\nEmployment & Earnings\\nState & Local Government\\nMetro Areas\\nFurther related statistics\\nFurther Content: You might find this interesting as well\\nStatistics\\nTopics Other statistics on the topicCalifornia\\nEconomy\\nU.S. leading companies headquartered in California 2023, by number of employees\\nEconomy\\nU.S. average annual wages in California 2018-2026\\nEconomy\\nU.S. California fastest growing private companies 2023, by three year growth rate\\nResidential Real Estate\\nHourly wages needed to afford a two-bedroom apartment in California 2021-23, by metro\\nYou only have access to basic statistics.\\n Additional Information\\nShow sources information\\nShow publisher information\\nUse Ask Statista Research Service\\nMarch 2023\\nUnited States\\n2000 to 2022\\nData presented here is in 2012 chained U.S. dollars.\\n Transforming data into design:\\nStatista Content & Design\\nStrategy and business building for the data-driven economy:\\nU.S. real GDP of California 2000-2022\\nReal gross domestic product of California in the United States from 2000 to 2022\\n(in billion U.S. dollars)\\n"}, {"url": "https://www.bea.gov/news/2024/gross-domestic-product-fourth-quarter-and-year-2023-advance-estimate", "content": "Gross Domestic Product, Fourth Quarter and Year 2023 (Advance Estimate) | U.S. Bureau of Economic Analysis (BEA) Real gross domestic product (GDP) increased at an annual rate of 3.3 percent in the fourth quarter of 2023 (table 1), according to the \\"advance\\" estimate released by the Bureau of Economic Analysis. The price index for gross domestic purchases increased 1.9 percent in the fourth quarter, compared with an increase of 2.9 percent in the third quarter (table 4). BEA releases three vintages of the current quarterly estimate for GDP. Unlike GDP, advance current quarterly estimates of GDI and corporate profits are not released because data on domestic profits and net interest of domestic industries are not available."}]', name='tavily_search_results_json', id='ae678022-d845-45fc-8273-e6d145ee952d', tool_call_id='call_-9181536546572673494', artifact={'query': 'latest GDP of California 2023', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': "California Remains the World's 5th Largest Economy", 'url': 'https://www.gov.ca.gov/2024/04/16/california-remains-the-worlds-5th-largest-economy/', 'content': 'California remains the 5th largest economy in the world since 2017. California is the 5th largest economy in the world for the seventh consecutive year, with a nominal GDP of nearly $3.9 trillion in 2023 and a growth rate of 6.1% since the year prior, according to the U.S. Bureau of Economic Analysis (BEA). On a per capita basis, California is', 'score': 0.9961755, 'raw_content': None}, {'title': 'Real GDP California U.S. 2023 | Statista', 'url': 'https://www.statista.com/statistics/187834/gdp-of-the-us-federal-state-of-california-since-1997/', 'content': 'Industry Overview\nDigital & Trend reports\nOverview and forecasts on trending topics\nIndustry & Market reports\nIndustry and market insights and forecasts\nCompanies & Products reports\nKey figures and rankings about companies and products\nConsumer & Brand reports\nConsumer and brand insights and preferences in various industries\nPolitics & Society reports\nDetailed information about political and social topics\nCountry & Region reports\nAll key figures about countries and regions\nMarket forecast and expert KPIs for 1000+ markets in 190+ countries & territories\nInsights on consumer attitudes and behavior worldwide\nBusiness information on 100m+ public and private companies\nExplore Company Insights\nDetailed information for 39,000+ online stores and marketplaces\nDirectly accessible data for 170 industries from 150+ countries\nand over 1\xa0Mio. facts.\n Statistics on\n"\nCalifornia\n"\nOther statistics that may interest you California\nPopulation\nEconomy\nEmployment & Earnings\nState & Local Government\nMetro Areas\nFurther related statistics\nFurther Content: You might find this interesting as well\nStatistics\nTopics Other statistics on the topicCalifornia\nEconomy\nU.S. leading companies headquartered in California 2023, by number of employees\nEconomy\nU.S. average annual wages in California 2018-2026\nEconomy\nU.S. California fastest growing private companies 2023, by three year growth rate\nResidential Real Estate\nHourly wages needed to afford a two-bedroom apartment in California 2021-23, by metro\nYou only have access to basic statistics.\n Additional Information\nShow sources information\nShow publisher information\nUse Ask Statista Research Service\nMarch 2023\nUnited States\n2000 to 2022\nData presented here is in 2012 chained U.S. dollars.\n Transforming data into design:\nStatista Content & Design\nStrategy and business building for the data-driven economy:\nU.S. real GDP of California 2000-2022\nReal gross domestic product of California in the United States from 2000 to 2022\n(in billion U.S. dollars)\n', 'score': 0.60323083, 'raw_content': None}, {'title': 'Gross Domestic Product, Fourth Quarter and Year 2023 (Advance Estimate)', 'url': 'https://www.bea.gov/news/2024/gross-domestic-product-fourth-quarter-and-year-2023-advance-estimate', 'content': 'Gross Domestic Product, Fourth Quarter and Year 2023 (Advance Estimate) | U.S. Bureau of Economic Analysis (BEA) Real gross domestic product (GDP) increased at an annual rate of 3.3 percent in the fourth quarter of 2023 (table 1), according to the "advance" estimate released by the Bureau of Economic Analysis. The price index for gross domestic purchases increased 1.9 percent in the fourth quarter, compared with an increase of 2.9 percent in the third quarter (table 4). BEA releases three vintages of the current quarterly estimate for GDP. Unlike GDP, advance current quarterly estimates of GDI and corporate profits are not released because data on domestic profits and net interest of domestic industries are not available.', 'score': 0.5940803, 'raw_content': None}], 'response_time': 2.92})]}})
----
(('researcher:1c6c3cb9-b2d8-3632-e480-a307b53f1d77',), {'agent': {'messages': [AIMessage(content="The latest GDP of New York in 2023 is approximately $2,172,010 million, and the latest GDP of California in 2023 is nearly $3.9 trillion, which is $3,900,000 million.\n\nTo calculate the average GDP of the two states, you would add these two figures together and then divide by 2. \n\nPlease note that for accurate calculations, it's important to ensure that the units are consistent (both in millions or both in trillions). The figures provided here are in millions. \n\nYou can proceed with the calculation using these figures.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 121, 'prompt_tokens': 1587, 'total_tokens': 1708, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-752b03c7-f372-447d-9440-97b513f0ae2b-0', usage_metadata={'input_tokens': 1587, 'output_tokens': 121, 'total_tokens': 1708, 'input_token_details': {}, 'output_token_details': {}})]}})
----
((), {'researcher': {'messages': [HumanMessage(content="The latest GDP of New York in 2023 is approximately $2,172,010 million, and the latest GDP of California in 2023 is nearly $3.9 trillion, which is $3,900,000 million.\n\nTo calculate the average GDP of the two states, you would add these two figures together and then divide by 2. \n\nPlease note that for accurate calculations, it's important to ensure that the units are consistent (both in millions or both in trillions). The figures provided here are in millions. \n\nYou can proceed with the calculation using these figures.", additional_kwargs={}, response_metadata={}, name='researcher')]}})
----
((), {'supervisor': {'next': 'coder'}})
----
(('coder:08b90861-7717-a01e-8178-a2245ce71495',), {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_-9181530190019420575', 'function': {'arguments': '{\n    "code": "def calculate_average_gdp(gdp_new_york, gdp_california):\\n    return (gdp_new_york + gdp_california) / 2\\n\\n# GDP values in millions\\nlatest_gdp_new_york = 2172010\\nlatest_gdp_california = 3900000\\n\\naverage_gdp = calculate_average_gdp(latest_gdp_new_york, latest_gdp_california)\\nprint(f\\"The average GDP of New York and California is: {average_gdp} million\\")\\n"\n}', 'name': 'code_executor'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 123, 'prompt_tokens': 316, 'total_tokens': 439, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-ccf3ab4e-8e24-480c-8935-b09236974eeb-0', tool_calls=[{'name': 'code_executor', 'args': {'code': 'def calculate_average_gdp(gdp_new_york, gdp_california):\n    return (gdp_new_york + gdp_california) / 2\n\n# GDP values in millions\nlatest_gdp_new_york = 2172010\nlatest_gdp_california = 3900000\n\naverage_gdp = calculate_average_gdp(latest_gdp_new_york, latest_gdp_california)\nprint(f"The average GDP of New York and California is: {average_gdp} million")\n'}, 'id': 'call_-9181530190019420575', 'type': 'tool_call'}], usage_metadata={'input_tokens': 316, 'output_tokens': 123, 'total_tokens': 439, 'input_token_details': {}, 'output_token_details': {}})]}})
----
(('coder:08b90861-7717-a01e-8178-a2245ce71495',), {'tools': {'messages': [ToolMessage(content='The result is:The average GDP of New York and California is: 3036005.0 million\n', name='code_executor', id='63ae3dcf-e81d-49f9-a705-1d87091554e8', tool_call_id='call_-9181530190019420575')]}})
----
(('coder:08b90861-7717-a01e-8178-a2245ce71495',), {'agent': {'messages': [AIMessage(content='The average GDP of New York and California is approximately 3,036,005 million. This figure represents the midpoint of their respective GDPs, providing a general sense of the economic scale of these two states combined.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 47, 'prompt_tokens': 459, 'total_tokens': 506, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-df630065-cd91-45ba-9fab-376ec79f9f60-0', usage_metadata={'input_tokens': 459, 'output_tokens': 47, 'total_tokens': 506, 'input_token_details': {}, 'output_token_details': {}})]}})
----
((), {'coder': {'messages': [HumanMessage(content='The average GDP of New York and California is approximately 3,036,005 million. This figure represents the midpoint of their respective GDPs, providing a general sense of the economic scale of these two states combined.', additional_kwargs={}, response_metadata={}, name='coder')]}})
----
((), {'supervisor': {'next': '__end__'}})
----

参考链接:https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/

如果有任何问题,欢迎在评论区提问。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/34656.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

前缀和(七) 连续数组中最长的01个数相等序列

525. 连续数组 给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组&#xff0c;并返回该子数组的长度。 示例 1: 输入: nums [0,1] 输出: 2 说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。 示例 2: 输入: nums [0,1,0] 输出: 2 说明: [0, 1] (或…

【硬件测试】基于FPGA的64QAM基带通信系统开发与硬件片内测试,包含信道模块,误码统计模块,可设置SNR

目录 1.算法仿真效果 2.算法涉及理论知识概要 2.1 64QAM调制解调系统的设计 2.2 信号解调 3.Verilog核心程序 4.开发板使用说明和如何移植不同的开发板 5.完整算法代码文件获得 1.算法仿真效果 本文是之前写的文章: 《基于FPGA的64QAM基带通信系统,包含testbench,高斯…

BUUCTF:misc刷题记录2(会持续更新的)

乌镇峰会种图 打开之后什么也没有发现 用010找到flag flag{97314e7864a8f62627b26f3f998c37f1} wireshark 解压后是个压缩包&#xff0c;用wirshark打开。 根据题目信息&#xff0c;我们可以在wirshark中去寻找密码 在这里进行过滤http.request.methodPOST 在这里的ffb7567a1…

elasticSearch(一):elasticSearch介绍

一、搜索引擎 搜索引擎的核心目的是帮助用户以最小的成本才海量数据中找到最想要的结果。糟糕的搜索引擎往往会所问非所答&#xff0c;用户查了半天也得不到自己想要的&#xff0c;好的搜索引擎往往第一页就是用户最想要的结果。而目前判断搜索引擎好坏一般是从召回率、精确率…

python解析各城市历史天气数据

1 背景介绍 python解析各城市历史天气数据 2 基本思路 获取原始数据&#xff0c;解析&#xff0c;然后保存到excel表格里面。 以浙江省杭州市西湖区2016年9月到2017年4月的 历史天气数据为例&#xff0c;最终成果如下&#xff1a; 3 核心代码 对于数据比较少时&#xff…

【并集查询】.NET开源 ORM 框架 SqlSugar 系列

.NET开源 ORM 框架 SqlSugar 系列 【开篇】.NET开源 ORM 框架 SqlSugar 系列【入门必看】.NET开源 ORM 框架 SqlSugar 系列【实体配置】.NET开源 ORM 框架 SqlSugar 系列【Db First】.NET开源 ORM 框架 SqlSugar 系列【Code First】.NET开源 ORM 框架 SqlSugar 系列【数据事务…

组件中的生命周期

文章目录 1 概念介绍2 使用方法3 示例代码我们在上一章回中介绍了Flutter中如何使用三方包相关的内容,本章回中将介绍Widget的生命周期.闲话休提,让我们一起Talk Flutter吧。 1 概念介绍 本章回中介绍的生命周期是指Widget从创建到结果的整个过程,这里提到的Widget是一个泛…

DAY35|动态规划Part03|LeetCode:01背包问题 二维、01背包问题 一维、416. 分割等和子集

目录 01背包理论基础&#xff08;一&#xff09; 基本思路 C代码 01背包理论基础&#xff08;二&#xff09; 基本思路 C代码 LeetCode:416. 分割等和子集 基本思路 C代码 01背包理论基础&#xff08;一&#xff09; 题目链接&#xff1a;卡码网46. 携带研究材料 文字…

Shopee大卖选品策略揭秘:印尼市场选品与成本分析案例

东南亚电商市场愈发成熟&#xff0c;越来越多做跨境的卖家转向本土。但对于“本土化选品运营”这个问题还相当疑惑&#xff01;看别人本土店销量飞起&#xff0c;自己却还在就纠结做啥能挣钱&#xff1f; 别急&#xff0c;今天EasyBoss根据之前合作的Shopee大卖分享的经验&…

鸿蒙特色实战2

服务卡片开发 创建服务卡片 创建一个新的工程后&#xff0c;可以通过如下方法进行创建服务卡片&#xff1a; 创建服务卡片包括如下两种方式&#xff1a; 选择模块&#xff08;如entry模块&#xff09;下的任意文件&#xff0c;单击菜单栏File > New > Service Widget创…

php基础:文件处理2

1.文件属性 当我们在程序中操作文件时&#xff0c;可能会使用到文件的一些常见属性&#xff0c;比如文件的大小、类型、修改时间、访问时间以及权限等等。PHP 中提供了非常全面的用来获取这些属性的内置函数&#xff0c;如下表所示。 2.目录操作 新建目录&#xff1a;mkdir(路…

激活函数在神经网络中的应用与选择

目录 ​编辑 Sigmoid函数 代码示例与分析 Tanh函数 代码示例与分析 ReLU函数 代码示例与分析 Leaky ReLU函数 代码示例与分析 PReLU函数 代码示例与分析 ELU函数 代码示例与分析 SELU函数 代码示例与分析 Softmax函数 代码示例与分析 结论 在深度学习领域&am…

如何在.NET 8.0 上安装 FastReport 并创建简单报告(下)

FastReport 是一款灵活而强大的报告工具。它允许用户以各种格式访问数据源并以可视化方式呈现它们。使用 FastReport 创建的报告可以在用户界面中使用拖放逻辑轻松设计&#xff0c;并转换为不同的格式&#xff08;PDF、Excel、Word 等&#xff09;。>> 如何在.NET 8.0 上…

SpringBoot期末知识点大全

一、学什么 IoC AOP&#xff1a;面向切面编程。 事物处理 整合MyBatis Spring框架思想&#xff01; 二、核心概念 问题&#xff1a;类之间互相调用/实现&#xff0c;导致代码耦合度高。 解决&#xff1a;使用对象时&#xff0c;程序中不主动new对象&#xff0c;转换为由外部提…

vscode CMakeLists中对opencv eigen的引用方法

CMakeLists.txt 项目模式&#xff08;只有一个main函数入口&#xff09; cmake_minimum_required(VERSION 3.5)project(vsin01 VERSION 0.1 LANGUAGES CXX)set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON)set(OpenCV_DIR G:/MinGW_Opencv/opencv4.10/opencv…

11.15【JAVA】【网络编程】【DEBUG】

代码以开源至cqujk/CquJavaEE 的myExp-socketCode分支,欢迎拷打 参考REPO Java 11: Standardized HTTP Client API 没反应 这是因为这应当是两个线程,当server创建好套接字后,进入accept时,就不会继续向下运行,客户端自然也就无法发送请求 首先要保证server进入accept(这个…

华为HCIE-Datacom认证笔试+实验考试介绍

华为HCIE数通认证考试是面向那些希望成为数通网络领域专家的人员&#xff0c;考试通常两部分&#xff1a;笔试和实验考试。 考试科目&#xff1a; HCIE-Datacom笔试考试内容&#xff1a; HCIE-Datacom V1.0考试覆盖数据通信领域路由交换高阶技术、企业网络架构全景、园区网络…

Android环境搭建

Android环境搭建 第一步&#xff1a;安装 Homebrew 执行以下命令来安装 Homebrew&#xff1a; /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"检测是否安装成功&#xff1a; brew --version第二步&#xff1a;安装 No…

WLAN漫游

定义 WLAN漫游 是指STA在不同AP覆盖范围之间移动且保持用户业务不中断的行为 实现WLAN漫游的两个AP必须使用相同的SSID和安全模板&#xff08;安全模板名称可以不同&#xff0c;但是安全模板下的配置必须相同&#xff09;&#xff0c;认证模板的认证方式和认证参数也要配置相…

排序2(万字详细版)

一 快速排序 快速排序是Hoare于1962年提出的⼀种⼆叉树结构的交换排序⽅法&#xff0c;其基本思想为&#xff1a;任取待排序元素 序列中的某元素作为基准值&#xff0c;按照该排序码将待排序集合分割成两⼦序列&#xff0c;左⼦序列中所有元素均⼩ 于基准值&#xff0c;右⼦序列…